您的位置:首页 > 其它

leetcode之Validate Binary Search Tree

2014-05-07 22:27 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.

这道题有两种思路,第一种思路如下:
可以利用二叉搜索树中序遍历有序的规则对二叉搜索树进行中序遍历,并将遍历的节点值存入栈中,在入栈的同时判断是否满足逐渐增大的条件如果满足则继续入栈,否则返回false,最终返回值为左子树返回值&&右子树返回值,其中边入栈边判断大小的思想是一种动态规划的思想。

bool isValidBST(TreeNode *root) {
if(root == NULL || (root->left == NULL && root->right == NULL))
return true;
stack<int>s;
return inOrder(root,s);

}
bool inOrder(TreeNode *root,stack<int>&s){
if(root == NULL)
return true;
bool b1 = inOrder(root->left,s);
if(!s.empty() && s.top() >= root->val)
return false;
s.push(root->val);
bool b2 = inOrder(root->right,s);
return b1 && b2;
}
另一种思路是:

根据二叉搜索树的性质,在判断左右子树的同时分别改变上下限,这种方法的实现不需要借助额外的内存空间,而且代码比较精简:

bool isValidBST(TreeNode *root) {
return valid(root,INT_MIN,INT_MAX);
}
bool valid(TreeNode *root,int min,int max){
if(root == NULL)
return true;
if(root->val <= min || root->val >= max)
return false;
return valid(root->left,min,root->val) && valid(root->right,root->val,max);
}


总之,上述两种方法都是借助二叉树的某种性质来判断当前二叉树是否是二叉搜索树,用来判断的这种性质必须是二叉搜索树的充分必要条件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: