您的位置:首页 > 其它

Leetcode 98. Validate Binary Search Tree

2018-03-29 16:07 489 查看
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
int left_max(TreeNode root)//root就是根的左孩子 找出左子树中最大的值(左子树中最右面的孩子)
{
int ans=root.val;
TreeNode Right=root.right;
while(Right!=null)
{
if(Right.val<=ans)//如果右子树小于根 返回整形最大值
{
return Integer.MAX_VALUE;
}
ans=Right.val;
Right=Right.right;
}
return ans;
}
int right_min(TreeNode root)//root就是根的右孩子 找出右子树中最小的值(右子树中最左面的孩子)
{
int ans=root.val;
TreeNode Left=root.left;
while(Left!=null)
{
if(Left.val>=ans)//如果左子树大于根 返回整形最min值
{
return Integer.MIN_VALUE;
}
ans=Left.val;
// Left=Left.right;//这里写错了
Left=Left.left;
}
return ans;
}
public boolean isValidBST(TreeNode root)
{
boolean ans=true;
if(root==null)return true;
if(root.left!=null&&root.val<=left_max(root.left))//如果左子树不为空且根<=左子树最大值 false
{
return false;
}
if(root.right!=null&&root.val>=right_min(root.right))//如果you子树不为空且根>=右子树最小值 false
{
return false;
}
if(root.left!=null||root.right!=null)
{
return isValidBST(root.left)&&isValidBST(root.right);
}
return ans;//左右子书都是空 返回true
}
}
解法:判断一棵树是不是二叉搜索树,如果根为空,返回是。其余判断根是不是比左子树最大值大,右子树最小值小,如果有左右子树,再去递归计算它的左子树和右子树的与运算,如果没有子树,返回true。左子树的最大值是最右面的节点,途中出现右子树比根小的,答案返回int的最大值,右子树最小值同理可得,小心复制代码的时候没有修改左右。
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.
Example 1:
2
/ \
1 3
Binary tree 
[2,1,3]
, return true.Example 2:
1
/ \
2 3
Binary tree 
[1,2,3]
, return false.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: