Inorder traversal the tree and compare one by one.

 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     void getTree(vector<int> &result, TreeNode *root) {
13         if (!root) return;
14         getTree(result, root->left);
15         result.push_back(root->val);
16         getTree(result, root->right);
17     }
18     bool isValidBST(TreeNode *root) {
19         if (!root) return true;
20         vector<int> result;
21         getTree(result, root);
22         for (int i = 0; i < result.size()-1; i++) {
23             if (result[i] >= result[i+1]) return false;
24         }
25         return true;
26     }
27 };

 

 

Another method is use BST properties. Then constrains two boundaries. But this does not work not. There are couple edge cases related with INT_MAX and INT_MIN;

 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 isValid(TreeNode *root, int lMin, int lMax) {
13         if (!root) return true;
14         if (root->val <= lMin || root->val >= lMax) return false;
15         return isValid(root->left, lMin, root->val) && isValid(root->right, root->val, lMax);
16     }
17     bool isValidBST(TreeNode *root) {
18         if (!root) return true;
19         return isValid(root, INT_MIN, INT_MAX);
20     }
21 };

 

posted on 2015-03-25 08:00  keepshuatishuati  阅读(108)  评论(0编辑  收藏  举报