My Java Recursion Solution


  • 0
    F
    public class Solution {
    public boolean isValidBST(TreeNode root) {
        boolean isValidLeft = true;
        boolean isValidRight = true;
        
        if(root != null){
            int val = root.val;
            if(root.left != null){
                //验证左子树是否为二叉搜索树,并且根节点大于左子树的最大值
                isValidLeft = isValidBST(root.left) && (val > fetchMaxNodeVal(root.left));
            }
            if(root.right != null){
                //验证右子树是否为二叉搜索树,并且根节点小于右子树的最小值
                isValidRight = isValidBST(root.right) && (val < fetchMinNodeVal(root.right));
            }
            if(root.left == null && root.right == null){
                return true;
            }
        }
        
        return isValidLeft && isValidRight;
    }
    
    //获取二叉树的最大值
    private int fetchMaxNodeVal(TreeNode node){
        while(node.right != null){
            node = node.right;
        }
        return node.val;
    }
    
    //获取二叉树的最小值
    private int fetchMinNodeVal(TreeNode node){
        while(node.left != null){
            node = node.left;
        }
        return node.val;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.