Validate Binary Search Tree

来源:互联网 发布:mac哑光橘红色 编辑:程序博客网 时间:2024/06/10 07:01

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

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

一开始考虑的不是很周全,是这样写的,

/** * 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) {        if(root==null) return true;        TreeNode left = root.left;        TreeNode right = root.right;        if(root.val>=right||root.val<=left) return false;        return isValidBST(left)&&isValidBST(right);    }}
也没有仔细想一想就直接提交了,反馈是wa。

再理了下发现主要是在这里只考虑了做孩子结点小于父节点,右孩子结点大于父节点。但是实际上,比如下面的例子:

                   4

         2                    6

1              3       5             7


同时还要满足3小于4.

也就是所有的左子树上的结点都要小于父节点,右子树的结点都要大于父节点。相当于,每个结点都有个区间范围x>low&&x<high,这样,题目可以理解成,每个结点是否都在范围(low,high)内。如果都在,则为true,否则,为false。如此以来,递归的参数就要包括,当前要比较的结点,以及low,high。

代码如下:

/** * 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,null,null);    }    private boolean isValidBST(TreeNode root, Integer low, Integer high) {        if(root==null) return true;        return (low==null||root.val>low)&&(high==null||root.val<high)&&isValidBST(root.left,low,root.val)            &&isValidBST(root.right,root.val,high);    }}
上面的代码考虑中需要注意一开始传递的参数值,(root,null,null)

0 0
原创粉丝点击