Leetcode 98. Validate Binary Search Tree

90 篇文章 0 订阅
29 篇文章 0 订阅
/**
 * 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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值