您的位置:首页 > 其它

验证二叉查找树

2015-08-26 23:28 316 查看
给定一个二叉树,判断它是否是合法的二叉查找树(BST)

一棵BST定义为:

节点的左子树中的值要严格小于该节点的值。

节点的右子树中的值要严格大于该节点的值。

左右子树也必须是二叉查找树。

样例

一个例子:
1
/ \
2   3
/
4
\
5


上述这棵二叉树序列化为
"{1,2,3,#,#,4,#,#,5}"
.


/**
* Definition of TreeNode:
* class TreeNode {
* public:
*     int val;
*     TreeNode *left, *right;
*     TreeNode(int val) {
*         this->val = val;
*         this->left = this->right = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
bool isValidBST(TreeNode *root) {
// write your code here
if (root == NULL)
{
return true;
}

if (root->left != NULL)
{
if (root->val <= root->left->val)
{
return false;
}

int leftMax = findMax(root->left);
if (root->val <= leftMax)
{
return false;
}
}

if (root->right != NULL)
{
if (root->val >= root->right->val)
{
return false;
}

int rightMin = findMin(root->right);
if (root->val >= rightMin)
{
return false;
}
}

return isValidBST(root->left) && isValidBST(root->right);
}
private:
int findMin(TreeNode *root)
{
TreeNode *p = root;
while (p->left != NULL)
{
p = p->left;
}

return p->val;
}

int findMax(TreeNode *root)
{
TreeNode *p = root;
while (p->right != NULL)
{
p = p->right;
}

return p->val;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: