一. 问题描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/
1 3
输出: true
示例 2:
输入:
5
/
1 4
/
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
二. 解题思路
本题思路:采用深度优先搜索+上下界确定的算法原理,利用递归方法进行求解。
步骤一:了解其上下界,对于左子树,其上界是当前的值,而下界则无需判断,但是需要为左子树的右子树进行保留,直接进行传递。对于右子树,其下界是当前节点的值,而上界则是为右子树的左子树进行保留,直接将该上界的值进行保留传递。
步骤二:构建递归函数(当前判断节点node,下界值lower,上界值higher);
步骤三:进行判断,如果对于val值小于lower则返回false;如果,val值大于higher值则返回false;
步骤四:进行新的递归函数,对于左子树构建(node.left,lower,val),对于右子树构建(node.right,val,heigh)。
步骤五:当某一个递归函数返回false;则总返回false.否则,返回true。
三. 执行结果
执行用时 :1 ms, 在所有 java 提交中击败了98.87%的用户
内存消耗 :36.7 MB, 在所有 java 提交中击败了93.46%的用户
四. Java代码
class Solution { public boolean isValidBST(TreeNode root) { return getnode(root,null,null); } public boolean getnode(TreeNode node,Integer lower,Integer higher) { if(node==null) { return true; } int val=node.val; if(lower!=null&&val<=lower) return false; if(higher!=null&&val>=higher) return false; if(!getnode(node.left,lower,val)) return false; if(!getnode(node.right,val,higher)) return false; return true; } }