题目
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);
}
};