Q: Given a binary tree, determine whether it is a valid binary search tree.
Suppose a binary search tree has the following characteristics:
The left subtree of a node contains only less than the current node.
The right subtree of a node contains only the number greater than the current node.
All left and right subtrees must themselves be binary search trees.
Example 1:
Input:
2
/
1 3
Output: true
Example 2:
Input:
5
/
14
/
36
Output: false
interpretation: Input as: [5,1,4, null, null, 3,6].
The root node has a value of 5, but its right child node has a value of 4.
A:
I found that I made two mistakes, both of which initially thought to traverse all nodes to ensure that node.right.val> node.val and node.left.val <node.val are valid for each node. But this is actually wrong. It should be that
the elements of the entire right subtree should be larger than the node.
In-order traversal. Every time I traverse to this point to see if it is larger than the previous point,
I started to save all the nodes and found that this is not necessary.
//这里我开始用的是Integer.MAX_VALUE,结果运行时直接用一个节点,节点数为Integer.MAX_VALUE。所以用的是Double
private double pre = -Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null)
return true;
return inorder(root);
}
private boolean inorder(TreeNode root) {
if (root == null)
return true;
boolean flag_left = inorder(root.left);
boolean flag = true;
if (root.val <= pre)
flag = false;
else
pre = root.val;
boolean flag_right = inorder(root.right);
return flag && flag_left && flag_right;
}