Validate Binary Search Tree [LeetCode]

 

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.
 1     bool varifyBST(TreeNode * root, int * out_min, int * out_max) {
 2         if(root == NULL)
 3             return true;
 4         (*out_min) = root->val;
 5         (*out_max) = root->val;
 6         if(root->left == NULL && root->right == NULL)
 7             return true;
 8         
 9         int vmax = root->val;
10         int vmin = root->val;
11         if(root->left != NULL){
12             bool ret = varifyBST(root->left, &vmin, &vmax);
13             if(ret == false)
14                 return false;
15             if(vmax >= root->val)
16                 return false;
17             (*out_min) = min(vmin, root->val);
18         }
19         
20         if(root->right != NULL){
21             bool ret = varifyBST(root->right, &vmin, &vmax);
22             if(ret == false)
23                 return false;
24             if(vmin <= root->val)
25                 return false;
26             (*out_max) = max(vmax, root->val);
27         }
28         return true;
29     }
30     
31     bool isValidBST(TreeNode *root) {
32         int vmax = 0;
33         int vmin = 0;
34         return varifyBST(root, &vmin, &vmax);
35     }

 

posted @ 2013-11-26 14:28  假日笛声  阅读(218)  评论(0编辑  收藏  举报