LeetCode algorithm recursive class - verify binary search tree

Table of contents

98. Verify Binary Search Tree

answer:

code:

Running results:​Edit


Given the root node of a binary tree  root , determine whether it is a valid binary search tree.

A valid  binary search tree is defined as follows:

  • A node's left subtree contains only numbers  less than  the current node.
  • The right subtree of a node contains only  numbers greater than  the current node.
  • All left and right subtrees must themselves be binary search trees.

Example 1:

Input: root = [2,1,3]
 Output: true

Example 2:

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

hint:

  • The number of nodes in the tree [1, 104] is within
  • -231 <= Node.val <= 231 - 1

题解:

 Inorder traversal : left root right - from small to large, so you only need to judge whether the current node is greater than the previous node (recursive)

The code has comments, the key lies in the understanding of ideas and some points of attention in the topic

① If the initialization pre is of int type, there may be boundary value influence and fail

②The position of the comparison part determines what type of traversal this is. For this question, traversing the left subtree first is in-order traversal

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //中序遍历:左根右——从小到大所以只需判断当前节点是否大于前一个节点(递归)
    long pre=Long.MIN_VALUE;//保留前一个数据(初始化为最小值)
    public boolean isValidBST(TreeNode root) {
        //终止条件:空树一定是有效的二叉搜索树
        if(root==null) return true;
        //中序遍历先遍历左子树
        if(isValidBST(root.left)==false) return false;
        //pre!=null时与当前节点值比较
        if(pre>=root.val){
            return false;
        }
        //pre<root.val就给他赋上这次节点的值方便下一个节点进行比较
        pre = root.val;

        return isValidBST(root.right);
    }
}

运行结果:

 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132231402