Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
思路:中序排列為排序好的數組(數組元素一次增大);數組中不能有重復元素。
代碼如下:
1 /**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode(int x) { val = x; }
8 * }
9 */
10 public class Solution {
11 public boolean isValidBST(TreeNode root) {
12
13 if(root==null||(root.left==null&&root.right==null))
14 return true;
15 ArrayList<Integer> list=ParentAndSon(root);
16 int[] nums=new int[list.size()];
17 int[] nums1=new int[list.size()];
18 for(int i=0;i<list.size();i++)
19 {
20 nums[i]=list.get(i);
21 nums1[i]=list.get(i);
22 }
23 Arrays.sort(nums);
24
25 if(nums[0]!=nums1[0])
26 return false;
27 for(int i=1;i<nums.length;i++)
28 {
29 if(nums1[i]!=nums[i]||nums[i]==nums[i-1])
30 return false;
31
32 }
33 return true;
34 }
35 public ArrayList<Integer> ParentAndSon(TreeNode root){
36 ArrayList<Integer> list=new ArrayList<>();
37 if(root.left!=null)
38 list.addAll(ParentAndSon(root.left));
39
40 list.add(root.val);
41
42 if(root.right!=null)
43 list.addAll(ParentAndSon(root.right));
44 return list;
45 }
46 }