recursive C# solution


  • 0
    K
    public class Solution {
        public bool IsValidBST(TreeNode root) {
            
            if (root == null) return true;
            
            return IsValid(root.val,root.right, "right") && IsValid(root.val,root.left, "left") && 
                   IsValidBST(root.right) && IsValidBST(root.left);
        }
        public bool IsValid(int val, TreeNode root, string way)
        {
            if (root == null) return true;
            
            bool b = false;
            if (way == "right") {
                if (val < root.val) 
                    b = IsValid(val, root.right, "right") && IsValid(val,root.left, "right");
            }
            else {
                if (val > root.val) 
                    b = IsValid(val, root.right, "left") && IsValid(val,root.left, "left");
            }
            return b;
        }
    }

Log in to reply
 

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