首页 > 其他 > 详细

LeetCode – Refresh – Valid Binary Search Tree

时间:2015-03-25 08:52:58      阅读:94      评论:0      收藏:0      [点我收藏+]

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 };

 

LeetCode – Refresh – Valid Binary Search Tree

原文:http://www.cnblogs.com/shuashuashua/p/4364636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!