Short and Clean Postorder Java Solution


  • 0
    J

    public class Solution {

    int max = 0;
    class Entity{
        int decLen;
        int incLen;
        public Entity(int incLen, int decLen){
            this.decLen = decLen;
            this.incLen = incLen; 
        }
    }
    
    public int longestConsecutive(TreeNode root) {
        dfs(root);
        return max;
    }
    
    public Entity dfs(TreeNode root){
        if(root==null){
            return new Entity(0,0);
        }
        Entity left = dfs(root.left);
        Entity right = dfs(root.right);
    
        int incLeft = (root.left==null||root.val==root.left.val+1)?left.incLen+1:1;
        int incRight = (root.right==null || root.val==root.right.val+1) ? right.incLen+1:1;
        int decLeft = (root.left==null||root.val==root.left.val-1)?left.decLen+1:1;
        int decRight = (root.right==null || root.val==root.right.val-1)?right.decLen+1:1;
        
        max = Math.max(max, incLeft+decRight-1);
        max = Math.max(max, incRight+decLeft-1);
        return new Entity(Math.max(incLeft, incRight), Math.max(decLeft, decRight));
    }
    

    }


Log in to reply
 

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