Java 1ms Solution


  • 0
    W

    '''
    public class Solution {
    public boolean isValidBST(TreeNode root) {
    return dfs(root);
    }
    private boolean dfs(TreeNode root){
    if(root==null)return true;
    //if(root.right==null&&root.left==null)return true;
    if(root.right!=null){if(root.val>=root.right.val)return false;}
    if(root.left!=null){if(root.val<=root.left.val)return false;}
    if(root.left!=null&&root.val<=dfsRight(root.left))return false;
    if(root.right!=null&&root.val>=dfsLeft(root.right))return false;
    return dfs(root.left)&&dfs(root.right);
    }
    private int dfsRight(TreeNode root){//递归找节点的最右子节点
    if(root.right!=null)return dfsRight(root.right);
    else{return root.val;}
    }
    private int dfsLeft(TreeNode root){//递归找节点的最左子节点
    if(root.left!=null)return dfsLeft(root.left);
    else{return root.val;}
    }
    }'''


Log in to reply
 

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