您的位置:首页 > 其它

LeetCode – Refresh – Valid Binary Search Tree

2015-03-25 08:00 288 查看
Inorder traversal the tree and compare one by one.

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void getTree(vector<int> &result, TreeNode *root) {
if (!root) return;
getTree(result, root->left);
result.push_back(root->val);
getTree(result, root->right);
}
bool isValidBST(TreeNode *root) {
if (!root) return true;
vector<int> result;
getTree(result, root);
for (int i = 0; i < result.size()-1; i++) {
if (result[i] >= result[i+1]) return false;
}
return true;
}
};


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;

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValid(TreeNode *root, int lMin, int lMax) {
if (!root) return true;
if (root->val <= lMin || root->val >= lMax) return false;
return isValid(root->left, lMin, root->val) && isValid(root->right, root->val, lMax);
}
bool isValidBST(TreeNode *root) {
if (!root) return true;
return isValid(root, INT_MIN, INT_MAX);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: