题目
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.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
思路
开始觉得这题目应该挺简单,直接递归左右子树,后来发现这个思路有很大的问题,只是保证左右子节点满足条件,而无法保证左子树的所有元素小于根节点(或者右子树所有元素大于根节点)。
这样的话可以想到用中序遍历来遍历所有节点,用递归实现中序遍历。
先遍历左子树,左子树不满足条件则返回false;
再查看根节点,如果根节点的值小于等于前面的部分则返回false;
最后遍历右子树。
二叉搜索树的中序遍历是一个递增的序列,所以这里用pre来表示中序遍历时当前结点前面的值,保证后面的值都比前面要小。
代码
/**
* 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:
TreeNode* pre=NULL;
bool isValidBST(TreeNode* root) {
if(root==NULL)
return true;
return inOrder(root);
}
bool inOrder(TreeNode* root) {
if(root==NULL)
return true;
if(!inOrder(root->left)) return false; //遍历左子树
if(pre != NULL && root->val <= pre->val) //查看根节点
return false;
pre = root;
return inOrder(root->right); //遍历右子树
}
};