标签:leetcode
在递归函数中,加上max和min,保存当前子树的最大值和最小值
合法的二叉查找树:
1.左子树最大值<根节点
2.右子树最小值>根节点
3.子树均为合法的BST
bool isValidBST(TreeNode *root) {
if (!root) return true;
int max, min;
return isValid(root, max, min);
}
bool isValid(TreeNode * root, int & max, int & min)
{
int subTreeMax, subTreeMin;
max = min = root->val;
if (root->left)
{
if (!isValid(root->left, subTreeMax, subTreeMin)) return false;
if (subTreeMax >= root->val) return false;
min = subTreeMin;
}
if (root->right)
{
if (!isValid(root->right, subTreeMax, subTreeMin)) return false;
if (subTreeMin <= root->val) return false;
max = subTreeMax;
}
return true;
}Validate Binary Search Tree [leetcode]
标签:leetcode
原文地址:http://blog.csdn.net/peerlessbloom/article/details/39581083