Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
confused what "{1,#,2,3}" means? >
read more on how binary tree is serialized on OJ.
The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.
Here‘s an example:
1
/ 2 3
/
4
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".由于二叉排序树的中序遍历序列是有序的,所以考虑在遍历的过程中通过判断遍历序列是否有序从而来判断该排序树是否有效,但这又涉及到第一个元素的问题,所以可以设一个比Integer.MAX_INT还小的值作为参考值或者设一个flag来判断是否是第一个值,第一个值直接跳过即可。
public boolean isValidBST(TreeNode root) {
if(root==null)
return true;
Stack<TreeNode>st=new Stack<TreeNode>();
st.push(root);
TreeNode top=null;
double temp=-2147483649.0;
while(!st.empty())
{
top=st.peek();
while(top.left!=null)
{
st.push(top.left);
top=top.left;
}
while(top.right==null)
{
if(temp<top.val)
temp=top.val;
else
return false;
st.pop();
if(!st.empty())
top=st.peek();
else
break;
}
if(!st.empty())
{
if(temp<top.val)
temp=top.val;
else
return false;
st.pop();
st.push(top.right);
}
}
return true;
}
leetcode_Validate Binary Search Tree
原文地址:http://blog.csdn.net/mnmlist/article/details/44875735