LeetCode Validate Binary Search Tree

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        return dfs(root, 0, 0, 0);
    }
    
    bool dfs(TreeNode *root, int lower, int upper, int part) {
        if (root == NULL) return true;
        if ((part & 0x1) && lower >= root->val) return false;
        if ((part & 0x2) && upper <= root->val) return false;
        return dfs(root->left, lower, root->val, part | 0x2) 
                && dfs(root->right, root->val, upper, part | 0x1);
    }
};

dfs,初最左边和最右边的分支(前者只有上界,后者只有下界),其他节点都有一个上界和下界,将节点值和这个范围比较即可。

第二轮:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

还可以使用中序遍历检测遍历得到的序列是否是递增的

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    bool val_set;
    int pre_val;
public:
    bool isValidBST(TreeNode *root) {
        val_set = false;
        return inorder(root);
    }
    
    bool inorder(TreeNode* root) {
        if (root == NULL) {
            return true;
        }
        if (!inorder(root->left)) {
            return false;
        }
        if (!val_set) {
            pre_val = root->val;
            val_set = true;
        } else {
            if (pre_val >= root->val) {
                return false;
            }
            pre_val = root->val;
        }
        return inorder(root->right);
    }
};

 

posted @ 2014-06-23 21:39  卖程序的小歪  阅读(114)  评论(0编辑  收藏  举报