98. Validate Binary Search Tree

JJ·2021년 1월 26일
0

Algorithms

목록 보기
84/114
class Solution {
    public boolean isValidBST(TreeNode root) {
        return helper(root);
    }
    
    public boolean helper(TreeNode root) {
        if (root.left == null || root.right == null) {
            return true; 
        }
        if (root.left.val > root.right.val) {
            return false;
        }
        
        helper(root.left);
        helper(root.right);
        return true; 
    }
}

41 / 77 test cases passed.

/**
 * 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 isValidBST(TreeNode root) {
        return helper(root, null, null);
    }
    
    public boolean helper(TreeNode root, int low, int high) {
        if (root == null) {
            return true; 
        }
        if ((low != null && root.val <= low) || (high != null && root.val >= high)) {
            return false;
        }
        
        return helper(root.right, root.val, high) && helper(root.left, low, root.val);
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Validate Binary Search Tree.
Memory Usage: 40.8 MB, less than 14.48% of Java online submissions for Validate Binary Search Tree.
전의 값이 중요! 한 tree에서만 X

0개의 댓글