[leetcode_98] Validate Binary Search Tree

判断一二叉棵树是否为BST。
结合BST的特征一直递归着找就行。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
    bool result;
    enum Flag {left, right, leftright};
    void isValidBSTStep(TreeNode * root, int val1, int val2, Flag flag) { 
        switch(flag){
            case left:
                if(root->val <= val1) {
                    result = false;
                    return;
                }
                break;
            case right:
                if(root->val >= val2) {
                    result = false;
                    return;
                }
                break;
            case leftright:
                if(root->val <= val1 || root->val >= val2) {
                    result = false;
                    return;
                }
                break;
        }
        if(root->left != NULL) {
            if(flag == left || flag == leftright)
                isValidBSTStep(root->left, val1, root->val, leftright);
            else
                isValidBSTStep(root->left, 0, root->val, right);
        }
        if(root->right != NULL ){
            if(flag == right || flag == leftright)
                isValidBSTStep(root->right, root->val, val2, leftright);
            else
                isValidBSTStep(root->right, root->val, 0, left);
        }
    }
    bool isValidBST(TreeNode *root) {
        result = true;
        if(root == NULL) return result;
        if(root->left != NULL) {
            isValidBSTStep(root->left, 0, root->val, right);
        }
        if(root->right != NULL ){
            isValidBSTStep(root->right, root->val, 0, left);
        }
        return result;
    }
};
Licensed under CC BY-NC-SA 4.0