Simple Java Solution


  • 0
    A

    DFS; note we can't assume min/max as Integer.MIN_VALUE/ Integer.MAX_VALUE.

    public boolean isValidBST(TreeNode root) {
        return helper(root, null, null);
    }
    
    private boolean helper(TreeNode root, Integer min, Integer max) {
        if (root == null)
            return true;
        else if ((min != null && root.val <= min) || (max != null && root.val >= max))
            return false;
        else
            return helper(root.left, min, root.val) && helper(root.right, root.val, max);
    }

  • 0
    H

    public boolean isValidBST(TreeNode root)
    {
    boolean isValid = true;
    List<Integer> list = inorderTraversal(root);
    for(int i=0;i<list.size()-1;i++)
    {
    if(list.get(i)>=list.get(i+1))
    {
    isValid = false;
    break;
    }
    }
    return isValid;
    }
    private List<Integer> inorderTraversal(TreeNode root)
    {
    List<Integer> list = new ArrayList<Integer>();
    if(root==null)
    return list;
    else
    {
    List<Integer> left = inorderTraversal(root.left);
    List<Integer> right = inorderTraversal(root.right);
    Iterator<Integer> ileft = left.iterator();
    while(ileft.hasNext())
    {
    list.add(ileft.next());
    }
    list.add(root.val);
    Iterator<Integer> iright = right.iterator();
    while(iright.hasNext())
    {
    list.add(iright.next());
    }
    return list;
    }
    }


Log in to reply
 

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