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.
思路:可用递归解决,我觉得唯一的难点在于要保证每次递归前,左子树的值均小于根植,右子树的值均大于根植。
(左右子树NULL节点均为满足判断条件的点)
/**
* 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 greatThanVal(int v,TreeNode *root)
{
if(NULL == root)
return true;
if(root->val > v)
return greatThanVal(v,root->left)&&greatThanVal(v,root->right);
return false;
}
bool lessThanVal(int v,TreeNode *root)
{
if(NULL == root)
return true;
if(root->val < v)
return lessThanVal(v,root->left)&&lessThanVal(v,root->right);
return false;
}
bool isValidBST(TreeNode* root) {
if(NULL == root)
return true;
if(NULL == root->left && NULL == root->right)
return true;
if(NULL == root->left)
{
if(greatThanVal(root->val,root->right))
return isValidBST(root->right);
else return false;
}
if(NULL == root->right)
{
if(lessThanVal(root->val,root->left))
return isValidBST(root->left);
else
return false;
}
if(greatThanVal(root->val,root->right)&&lessThanVal(root->val,root->left))
return isValidBST(root->left)&&isValidBST(root->right);
else
return false;
}
};