98. Validate Binary Search Tree

  不定期更新leetcode解题java答案。

  采用pick one的方式选择题目。 

  题目要求判断树是否为二叉搜索树。要求为:1、一个节点的左子树的所有节点均小于该节点;2、一个节点的右子树上的所有节点均大于该节点;3、所有节点均满足1,2的条件。

  容易想到采用递归的方式依次向下检测。递归需要传递的参数为下一需要检测的节点,以及该节点应满足的上下界的值;此外如果节点为最左侧或最右侧节点,不应检测其下界或上界。

  代码如下:

 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         return root == null ? true : isValidBST(root.left, Integer.MIN_VALUE, root.val, true, false) 
        && isValidBST(root.right, root.val, Integer.MAX_VALUE, false, true); 13 } 14 public boolean isValidBST(TreeNode root, int smallVal, int largeVal, boolean isLeft, boolean isRight){ 15 if(root == null) 16 return true; 17 else if((!isRight && root.val >= largeVal) || (!isLeft && root.val <= smallVal)) 18 return false; 19 else 20 return isValidBST(root.left, smallVal, root.val, isLeft, false) &&
          isValidBST(root.right, root.val, largeVal, false, isRight); 21 } 22 23 }

 

posted @ 2016-10-22 17:06  zslhq~  阅读(168)  评论(0编辑  收藏  举报