Java recursive


  • 0
    F

    Using ternary ops to avoid if/then statements:

    public class Solution {
        public int longest(TreeNode root, int len) {
            return Math.max(
                            Math.max(
                                    (root.left  == null) ? 
                                                    len : 
                                                    longest(root.left , (root.val+1 == root.left.val ) ? 
                                                                            len + 1 : 
                                                                            1), 
                                    len),
                            Math.max(
                                    (root.right == null) ? 
                                                    len : 
                                                    longest(root.right, (root.val+1 == root.right.val) ? 
                                                                            len + 1 : 
                                                                            1), 
                                    len));
        }
        
        public int longestConsecutive(TreeNode root) {
            if (root == null) { return 0; } else { return longest(root, 1); }
        }
    }
    

Log in to reply
 

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