Leetcode OJ 98 Validate Binary Search Tree [Medium]

来源:互联网 发布:股票统计软件手机 编辑:程序博客网 时间:2024/06/18 11:27

Leetcode OJ 98 Validate Binary Search Tree

题目描述:

Given a binary tree, determine if it is a valid binarysearch tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keysless than the node's key.

The right subtree of a node contains only nodes withkeys greater than the node's key.

Both the left and right subtrees must also be binarysearch trees.

Example 1:

    2

   / \

  1   3

Binary tree [2,1,3], return true.

Example 2:

    1

   / \

  2   3

Binary tree [1,2,3], return false.

题目理解:

判断一个二叉树是不是二叉查找树。

测试用例:

功能测试:[2,1,3];[10,5,15,null,null,6,20](父节点介于左节点和右节点间,但不是二叉搜索树);

特殊输入:二叉树是空;二叉树的节点是int边界值;

分析:

1.  一开始想到只要父节点介于左右节点之间就是二叉搜索树,但这是不对的比如[10,5,15,null,null,6,20];

2.  左节点小于父节点,大于最小值,最小值是继承下来的;

3.  右节点大于父节点,小于最大值,最大值是继承下来的;

4.  如果出现左节点大于等于父节点,或者小于等于最小值,则返回false;

5.  如果出现右节点小于等于父节点,或者大于等于最大值,则返回false;

6.  用递归实现,递归的边界是要检查的节点是null;

7.  最初设置的最小最大值要比int的边界更小/大;比如当输入[int.MAX_VALUE]时,返回值应是true;

解答:

/** * Definition for a binary tree node. * public class TreeNode { *    int val; *    TreeNode left; *    TreeNode right; *    TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isValidBST(TreeNode root) {        return isValidBSTNode(root,Long.MIN_VALUE,Long.MAX_VALUE);    }    public static boolean isValidBSTNode(TreeNode root,long minValue,long maxValue){        if(root== null) returntrue;        if(root.val<= minValue || root.val >= maxValue) return false;        return isValidBSTNode(root.left, minValue, root.val) && isValidBSTNode(root.right,root.val, maxValue);    }}


 

 

原创粉丝点击