题目:
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
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
分析:我最初的想法是使用递归,即左子节点小于根节点,右子节点大于根节点,但这样忽略了一个问题,递归的时候,右子节点的左子节点可能小于根节点,这样就不对了。我不知道该如何解决这个问题。
后来看了别人的代码才发现中序遍历可以解决这个问题。非递归的中序遍历自己写还是有点难度的,只有多练了。其实递归方法也是可以了,带我做第二遍的时候再记录下来吧。
中序、先序、后序遍历的非递归方法都有必要掌握。有关树的很多题目都可以用它们很快地解决。
代码:
bool inOrder(TreeNode* root){
if(!root){
return 1;
}
stack<TreeNode*> s;
TreeNode* pre = NULL;
while (root || !s.empty()){
while(root){
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
if(pre != NULL && pre->val >= root->val){
return false;
}
pre = root;
root = root->right;
}
return true;
}
bool isValidBST(TreeNode* root) {
return inOrder(root);
}