您的位置:首页 > 其它

LeetCode Validate Binary Search Tree

2014-12-19 10:40 169 查看
题目

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.

探测一个二叉树的合法性。

每个左子树上的点的值不能大于等于当前元素的值,每个右子树上的点的值不能小于等于当前值。

记录值的限制,递归调用即可。

代码:

/**
* 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 innerBST(TreeNode *root,long long min,long long max)	//迭代扫描,根,可以取的最小合法值,可以取的最大合法值
{
if(root==NULL)	//NULL为合法
return true;
if(root->left!=NULL&&(root->left->val>=root->val||root->left->val<=min))	//左子树的值是否合法
return false;
if(root->right!=NULL&&(root->right->val<=root->val||root->right->val>=max))	//右子树的值是否合法
return false;
if(innerBST(root->left,min,root->val)&&innerBST(root->right,root->val,max))	//判断左右子树是否合法
return true;
return false;	//否则不合法
}
bool isValidBST(TreeNode *root) {
return innerBST(root,(long long)LONG_MIN-1,(long long)LONG_MAX+1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: