[Modified post-order traversal] 98. Verify binary search tree

98. Verify binary search tree

Problem-solving ideas

  • Modified post-order traversal algorithm. Post-order traversal can carry parameters for traversal.
  • The subtree nodes with root as the root node must satisfy max.val > root.val > min.val
  • What needs to be done for a node
  • If the node is empty, directly true
  • If a node value is less than Min false
  • If a node value is greater than max false
  • Then the postorder traversal algorithm performs recursion
/**
 * 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 {
    
    

    public boolean isV(TreeNode root, TreeNode min,TreeNode max){
    
    
        // 以root为根节点的子树节点  必须满足 max.val > root.val > min.val
        if(root == null)
        {
    
    
            return true;
        }
        if(min != null && root.val <= min.val){
    
    
            return false;
        }
        if(max != null && root.val >= max.val){
    
    
            return false;
        }
        // 限定左子树的最大值是root.val  限定右子树的最小值是root.val
        return isV(root.left,min,root) && isV(root.right,root,max);
    }

    public boolean isValidBST(TreeNode root) {
    
    

            return isV(root,null,null);
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/133487085