您的位置:首页 > 其它

leetcode_Validate Binary Search Tree

2015-04-04 20:39 381 查看

描述:

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.

confused what 
"{1,#,2,3}"
 means? >
read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:
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;
}

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: