[Leetcode 76] 98 Validate Binary Search Tree

Problem:

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.

 

Analysis:

Tree problem always related to its recursive property. Here to judge whether a binary tree is a binary search tree, the condition is as follows.

   root

  /   \

left     right

 

left sub-tree's nodes' value should all less than the root's value

right sub-tree's nodes' valu should all greater than the root's value

And do it recursively. 

For the left-subtree, the max value is root->val and for right-subtree, the min value is root->val

Here the construction of initial max and min value is a little tricky by using the bit operation. 

 

Code:

 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         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         int max = (1<<31)-1;
16         int min = (1<<31);
17         
18         return judge(root, max, min);
19     } 
20     
21 private:
22     bool judge(TreeNode *n, int max, int min) {
23         if (n == NULL)
24             return true;
25             
26         if (n->val < max && n->val > min)
27             return judge(n->left, n->val, min) && judge(n->right, max, n->val);
28         else
29             return false;
30     }
31 };
View Code

 

posted on 2013-07-22 13:54  freeneng  阅读(233)  评论(0编辑  收藏  举报

导航