您的位置:首页 > 其它

Validate Binary Search Tree

2016-06-03 10:22 253 查看
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.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路:判断一个BST树是不是有效的。有效的BST树是这样一个树。

如果节点为NULL,则其是一个有效的BST。如果其含有左孩子,左孩子节点的值小于当前节点的val,如果其含有右孩子,右孩子节点的val大于当前节点的val值。其左右孩子也分别是一个BST。代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return helper(root,INT_MIN,INT_MAX);
}

bool helper(TreeNode *root,int min,int max) //core
{
if(root==NULL)
return true;
return root->val<max&&root->val>min&&helper(root->left,min,root->val)&&helper(root->right,root->val,max);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: