LeetCode-98. Verify Binary Search Tree-DFS

98. Verify Binary Search Tree

Title description

Given a binary tree, judge whether it is a valid binary search tree.

Suppose a binary search tree has the following characteristics:

The left subtree of the node only contains numbers less than the current node.
The right subtree of the node only contains numbers greater than the current node.
All left subtrees and right subtrees themselves must also be binary search trees.
Example 1:

enter:

    2
   / \
  1   3

Output: true
Example 2:

enter:

	    5
	   / \
	  1   4
	     / \
	    3   6

Output: false
Explanation: The input is: [5,1,4,null,null,3,6].
The value of the root node is 5, but the value of its right child node is 4.

Problem-solving ideas

 //用一个变量记录前一个节点
    long pre = Long.MIN_VALUE;
    public boolean isValidBST(TreeNode root) {
    
    
        if (root == null){
    
    
            return true;
        }
        //访问左子树
        if (!isValidBST(root.left)){
    
    
            return false;
        }
        //访问当前节点,如果当前节点小于等于中序遍历的前一个节点,说明不满足BST,返回false;否则继续遍历
        if (root.val <= pre){
    
    
            return false;
        }
        pre = root.val;
        //访问右子树
        return isValidBST(root.right);

    }
    public boolean isValidBST(TreeNode root){
    
    
        return recurse(root,null,null);
    }
    public boolean recurse(TreeNode node,Integer lower,Integer upper){
    
    
        //空节点是合理的二叉搜索树
        if (node == null){
    
    
            return true;
        }
        //节点不为空,判断节点上的值是否在上下界内
        int val = node.val;
        if (lower != null && val <= lower)return false;
        if (upper != null && val >= upper)return false;

        //将当前节点的值替换为下届,继续检查右边的子节点
        if (!recurse(node.right,val,upper))return false;
        //将当前节点的值替换为上界,继续检查左边的子节点
        if (!recurse(node.left,lower,val))return false;
        return true;
    }


Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115017122