您的位置:首页 > 其它

[Leetcode]Validate Binary Search Tree

2014-11-27 14:28 441 查看
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的性质。开始写了一个递归的方法,结果问题出在了INT_MAX和INT_MIN这两个值上,如果这两个值出现在树中,这个方法就不可行了。

class Solution {
public:
bool isValidBST(TreeNode *root) {
return check(root, INT_MAX, INT_MIN);
}
bool check(TreeNode *root, int max, int min){
if (NULL == root) return true;
if (root->val > min && root->val < max){
return check(root->left, root->val, min) && check(root->right, max, root->val);
}
else return false;
}
};

在网上翻了好久,发现很多之前AC的代码都是这么写的,说明leetcode有可能更新了test cases,加上了对INT_MAX和INT_MIN的检测,使这些代码没办法再AC了(就像reverse integar那道题一样)。这种思路时间复杂度是O(n),空间复杂度是O(0)。

这样的话,这种思路就行不通了。只能从BST的另一个性质出发,中序遍历这棵树,如果这棵树是BST,那么这个遍历结果正好的升序排列的,这样做空间复杂度也到达了O(n)。

class Solution {
public:
bool isValidBST(TreeNode *root) {
vector<int> result;
inorder(root, result);
for (int i = 1; i < result.size(); i++){
if (result[i - 1] >= result[i]) return false;
}
return true;
}
void inorder(TreeNode *root,vector<int> &result){
if (!root) return;
if (root->left) inorder(root->left, result);
result.push_back(root->val);
if (root->right) inorder(root->right, result);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode BST