The topic is from LeetCode
Other solutions or source code can be accessed: tongji4m3
description
Given a binary tree, judge whether it is a valid binary search tree.
Suppose a binary search tree has the following characteristics:
The left subtree of the node only contains numbers less than the current node.
The right subtree of the node only contains numbers greater than the current node.
All left and right subtrees must themselves be binary search trees.
Example 1:
输入:
2
/ \
1 3
输出: true
Example 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
Ideas
Mid-order traversal, if the following node is less than or equal to the previous node, it is not a binary search tree
detail
Use isFirst to avoid errors in the following special situations:
If the leftmost one happens to be Integer.MIN_VALUE or there are two Integer.MIN_VALUE
Code
public boolean isValidBST(TreeNode root)
{
Stack<TreeNode> stack=new Stack<>();
TreeNode temp = root;
boolean isFirst = true;
int pre=0;
while(temp!=null || !stack.isEmpty())
{
while(temp!=null)
{
stack.push(temp);
temp = temp.left;
}
temp = stack.pop();
if(isFirst)
{
pre = temp.val;
isFirst = false;
}
else if(temp.val<=pre)
{
return false;
}
pre = temp.val;
temp = temp.right;
}
return true;
}