驗證二叉查找樹(LintCode)

驗證二叉查找樹

給定一個二叉樹,判斷它是不是合法的二叉查找樹(BST)

一棵BST定義爲:ide

  • 節點的左子樹中的值要嚴格小於該節點的值。
  • 節點的右子樹中的值要嚴格大於該節點的值。
  • 左右子樹也必須是二叉查找樹。
樣例

一個例子:this

2
 / \
1   4
   / \
  3   5

上述這棵二叉樹序列化爲 {2,1,4,#,#,3,5}.spa

 

中序遍歷獲得中序遍歷序列,驗證是否遞增便可。code

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: The root of binary tree.
15      * @return: True if the binary tree is BST, or false
16      */
17      
18     public boolean isValidBST(TreeNode root) {
19         List<Integer> list = new ArrayList<Integer>();
20         midOrder(root,list);
21         for(int i=1;i<list.size();i++) {
22             if(list.get(i-1) >= list.get(i))return false;
23         }
24         
25         return true;
26     }
27     
28     public void midOrder(TreeNode root,List<Integer> list) {
29         if(root == null) return;
30         midOrder(root.left,list);
31         list.add(root.val);
32         midOrder(root.right,list);
33     }
34 }
View Code
相關文章
相關標籤/搜索