C# solution Beat 74%


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        bool helper(TreeNode node, ref long lastvalue)
        {
            bool result = true;
            
            // go to left
            if( node.left != null ) result &= helper(node.left, ref lastvalue);
            if( !result ) return false;
    
            // go to self
            result &= lastvalue < node.val;
            if( !result ) return false;
            lastvalue = node.val;
    
            // go to right
            if( node.right != null ) result &= helper(node.right, ref lastvalue);
            return result;
        }
        
        public bool IsValidBST(TreeNode root) 
        {
            if(root == null) return true;
            long firstvalue = ((long)int.MinValue) * 2;
            return helper(root, ref firstvalue);
        }
    }
    

Log in to reply
 

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