码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_Validate Binary Search Tree

时间:2015-04-04 21:15:48      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:二叉排序树   validate binary sear   

描述:

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;
    }

结果:

技术分享

leetcode_Validate Binary Search Tree

标签:二叉排序树   validate binary sear   

原文地址:http://blog.csdn.net/mnmlist/article/details/44875735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!