个人记录-LeetCode 98. Validate Binary Search Tree

来源:互联网 发布:fetch.js官网 编辑:程序博客网 时间:2024/06/06 02:52

问题:
Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:
1、The left subtree of a node contains only nodes with keys less than the node’s key.
2、The right subtree of a node contains only nodes with keys greater than the node’s key.
3、Both the left and right subtrees must also be binary search trees.

Example 1:

    2   / \  1   3

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

Example 2:

    1   / \  2   3

这个问题就是判断给定的树是否为二分查找树。

二分查找树的特点上文已经写的很清楚了:
要求根节点左子树节点的值全部小于根节点的值;
同时要求根节点右子树节点的值全部大于根节点的值。


代码示例:
对于这个问题,递归足以满足它的要求,
对应代码类似于:

/** * 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 isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);    }    private boolean isValidBST(TreeNode root, long minValue, long maxValue) {        //当前根节点为null时,返回true        if (root == null) {            return true;        }        //当前节点的值必须在minValue和maxValue之间        if (root.val <= minValue || root.val >= maxValue) {            return false;        }        //对于左子树,其最大值要小于root.val        //对于右子树,其最小值要大于root.val        return isValidBST(root.left, minValue, root.val)                && isValidBST(root.right, root.val, maxValue);    }}
0 0