您的位置:首页 > 其它

《leetCode》:Validate Binary Search Tree

2016-01-16 21:10 302 查看

题目

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.


思路

刚开始的思路为:先判断跟节点与左右子节点是否满足二叉搜索树的规则,然后递归到左子树和右子树是否满足二叉搜索树的规则。但是在实现过程中,没有将根节点的值传给左右子树,因此在出现{10,5,15,null,null,6,10}这样的情况时就不能正确的进行判断。

因此,在判断左右子树是否满足二叉搜索树的要求时,需要将根节点的值时时的传入进行。即将某一个子二叉树的各个节点的值的范围要进行一定的限制,只有这样,才能进行正确的判断。

最终实现的代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
//思路来源于:https://leetcode.com/discuss/74359/4-line-c-simple-solution-easy-understanding
bool isValidBST_v1(struct TreeNode* root,long low,long high){
if(root==NULL){
return true;
}
return (low<root->val)&&(root->val<high)&&(isValidBST_v1(root->left,low,root->val))&&(isValidBST_v1(root->right,root->val,high));
}
bool isValidBST(struct TreeNode* root) {
return isValidBST_v1(root,LONG_MIN,LONG_MAX);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: