您的位置:首页 > 其它

[leedcode 98] Validate Binary Search Tree

2015-07-16 22:17 253 查看
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.

/**
* 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) {
//[2147483647]
//注意,因为root的val是int型的,其可能为最大值或最小值,因此一开始的设置最大或最小要使用long型,注意函数参数的类型
//本题非常巧妙使用最大值和最小值限制根节点的范围。最关键是对isvalid的正确定义,代表root的值是否在min和max中间

//本题另一个解法是:将二叉树中序遍历,然后检测是否是递增数组
return isvalid(root,(long)Integer.MIN_VALUE-1,(long)Integer.MAX_VALUE+1);
}
public boolean isvalid(TreeNode root,long min,long max){
if(root==null){
return true;
}
long val=(long)root.val;
if(val>min&&val<max){
return isvalid(root.left,min,val)&&isvalid(root.right,val,max);
}else return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: