Java Clean Coded Solution


  • 0
    Z

    This solution is very strightforward and easy to understand. I recommend to read that first then come up with optimized version.

    public class Solution {
        
        private final int DECR = -1, INCR = 1;
        
        public int longestConsecutive(TreeNode root) {
            if(root == null) return 0;
            int incr = getLongestConseq(root, INCR), decr = getLongestConseq(root, DECR);
            return Math.max(incr+decr-1, Math.max(longestConsecutive(root.left), longestConsecutive(root.right)));
        }
        
        private int getLongestConseq(TreeNode root, int incr){
            if(root == null) return 0;
            int res = 0, next = root.val+incr;
            if(root.left != null && root.left.val == next){
                res = Math.max(res,getLongestConseq(root.left, incr));
            }
            if(root.right != null && root.right.val == next){
                res = Math.max(res, getLongestConseq(root.right,incr));
            }
            return res+1;
        }
    }

Log in to reply
 

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