[LeetCode] Validate Binary Search Tree

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.

解法一:曾经用pre_value = INT_MIN记录最小值,然后不断判断当前节点是否大于pre_value来判断。原来行,后来就不行了。INT_MIN似乎有bug(https://leetcode.com/discuss/14886/order-traversal-please-rely-buggy-int_max-int_min-solutions)。现在改用pre记录前一个节点来判断。

/**
 * 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) {
        if (!root) return true;
        stack<TreeNode*> s;
        TreeNode *p = root;
        TreeNode *pre = NULL;
        while (p || !s.empty()) {
            while (p) {
                s.push(p);
                p = p->left;
            }
            p = s.top();
            s.pop();
            if (!pre) pre = p;
            else {
                if (p->val <= pre->val) return false;
            }
            pre = p;
            p = p->right;
        }
        return true;
    }
};

 

解法二:递归的方法。时间复杂度O(n),空间复杂度O(logN)

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode *root) {
13         return isValidBST(root, LONG_MIN, LONG_MAX);
14     }
15     bool isValidBST(TreeNode *root, long lower_value, long upper_value) {
16         if (root == NULL) return true;
17         
18         return root->val > lower_value && root->val < upper_value
19                && isValidBST(root->left, lower_value, root->val)
20                && isValidBST(root->right, root->val, upper_value);
21     }
22 };

 

posted @ 2015-01-20 11:44  vincently  阅读(285)  评论(0编辑  收藏  举报