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.

 

BST 其实就是一个中跟遍历,中跟遍历后的顺序应该是排好序的!!!!

 

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode* root) {
 4         if (root == NULL)
 5             return true;
 6         if (root->left == NULL && root->right == NULL)
 7             return true;
 8         stack<TreeNode*> s;
 9         TreeNode* p = root; 
10         int left,flag;
11         flag = 0;
12         while(p)
13         {
14             while(p)
15             {
16                 s.push(p);
17                 p = p->left;
18             }
19             while(!s.empty())
20             {
21                 TreeNode * cur = s.top();
22                 s.pop();
23                 if(flag == 0)
24                 {
25                     flag = 1;
26                     left = cur->val;
27                 }
28                 else if(cur->val <= left)
29                     return false;
30                 left = cur->val;
31                 if(cur->right)
32                 {
33                     p = cur->right;
34                     break;
35                 }
36 
37             }
38             
39         }
40         return true;
41     }
42 };

 递归的方法:

 

引入全局变量

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode *root) {
 4         static int m = INT_MIN;
 5         if(root == NULL) return true;
 6         if(!isValidBST(root->left)) return false;
 7         if(!(root->val > m)) {
 8             return false;
 9         }
10         m = root->val;
11         return isValidBST(root->right);
12     }
13 };

 

posted on 2015-07-03 13:23  又岸  阅读(316)  评论(0)    收藏  举报