DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Valid Binary Search Tree

Problem

TC: O(n), SC: O(n)

/**
 * 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 isValid(root,-1001,1001);
    }
    // inorder dfs
    public boolean isValid(TreeNode root,int l, int r){
        if(root ==null) return true;
        boolean left = isValid(root.left,l,root.val);
        //root.val should always be greater than its left child value and less  that its right chil value
        if(root.val <=l || root.val>=r) return false;
        boolean right = isValid(root.right,root.val, r);
        return left &&  right;

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay