98. Validate Binary Search Tree

1. 判断是否是BST的逻辑

  1)左子树所有节点值都必须 小于 根节点的值

  2)右子树所有节点值都必须 大于 根节点的值

  3)左子树和右子树都必须也是BST

2. 所以helper函数的逻辑大概是:

  1)如果root是空,返回true

  2)如果当前节点值在允许的最小值很最大值之外,返回false

  3)返回左子树和右子树是否同时为真

3.helper函数重点:

  1)传入最小值和最大值作为参数

  2)如果某节点值是Integer.MIN_VALUE或者Integer.MAX_VALUE那么无法判断,所以要把参数都转换成Long

 

 1     public boolean isValidBST(TreeNode root) {
 2         if(root == null) {
 3             return true;
 4         }
 5         return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
 6     }
 7 
 8     private boolean helper(TreeNode root, long minValue, long maxValue) {
 9         if(root == null) {
10             return true;
11         }
12         if((long)root.val <= minValue || (long)root.val >= maxValue) {
13             return false;
14         }
15         return helper(root.left, minValue, (long)root.val) && helper(root.right, (long)root.val, maxValue);
16     }

 

posted @ 2016-06-04 04:31  warmland  阅读(177)  评论(0编辑  收藏  举报