Leetcode-98. Validate Binary Search Tree

问题描述


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.

给出一个二叉树,判断是不是二叉查找树。二叉查找树具有以下性质:

(1)左子树的值均小于根节点

(2)右子树的值均大于根节点

(3)所有的左右子树均遵循(1)(2)中的描述

问题解析


看到这个题目的时候我首先想到用二叉查找树的性质+递归进行判断。

但是这样会有一个问题。对于下图中的二叉树会做出错误的判断。


图中的节点(5)和节点(15)虽然对于单个节点来讲符合二叉查找树的条件,但整体上,这个树并不是一个二叉查找树。

于是进行改进,使用如下的判断条件:

(1)对于任意一个节点node,左子树上的最大值都小于node的值;

(2)对于任意一个节点node,右子树的最小值都大于node的值;

满足以上条件的二叉树一定是一个二叉查找树。

解析代码


public boolean isValidBST(TreeNode root) {
		if(root == null){
			return true;
		}
		Integer maxLeft = findMaxInLeftTree(root.left);
		if(maxLeft != null && maxLeft >= root.val){
			return false;
		}
		Integer minRight = findMinInRightTree(root.right);
		if(minRight != null && minRight <= root.val){
			return false;
		}
		if(!isValidBST(root.left)){
			return false;
		}
		if(!isValidBST(root.right)){
			return false;
		}
		return true;
	}
	
	
	private Integer findMaxInLeftTree(TreeNode left) {
		if(left == null){
			return null;
		}
		if(left.right == null){
			return left.val;
		}
		return findMaxInLeftTree(left.right);
	}
	
	private Integer findMinInRightTree(TreeNode right) {
		if(right == null){
			return null;
		}
		if(right.left == null){
			return right.val;
		}
		return findMinInRightTree(right.left);
	}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值