标签:
一棵BST定义为:
一个例子:
2
/ 1 4
/ 3 5
上述这棵二叉树序列化为 {2,1,4,#,#,3,5}
.
中序遍历得到中序遍历序列,验证是否递增即可。
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 }
标签:
原文地址:http://www.cnblogs.com/FJH1994/p/5025622.html