Java Postorder- a bit verbose


  • 0
    V
        int maxVal = 0;
        public int longestConsecutive(TreeNode root) 
        {
            int[] recVal = dfs(root);
            return Math.max(Math.max(recVal[0], recVal[1]), maxVal);
        }
        int[] dfs(TreeNode root)
        {
            if(root == null)
                return new int[2];
            int[] lval = dfs(root.left);
            int[] rval = dfs(root.right);
            int[] toRet = new int[2]; toRet[0] = toRet[1] = 1;
            if(root.left != null)
            {
                if(root.val + 1 == root.left.val)
                    toRet[1] = 1 + lval[1];
                if(root.val - 1 == root.left.val)
                    toRet[0] = 1 + lval[0];
            }
            if(root.right != null)
            {
                if(root.val + 1 == root.right.val)
                    toRet[1] = Math.max(toRet[1], 1 + rval[1]);
                if(root.val - 1 == root.right.val)
                    toRet[0] = Math.max(toRet[0], 1 + rval[0]);
            }
            if(root.left != null && root.right != null)
            {
    //check is contiguous seq 
                if(root.left.val + 1 == root.val && root.val + 1 == root.right.val) 
                    maxVal = Math.max(maxVal, 1 + lval[0] + rval[1]);
                if(root.left.val == root.val + 1 && root.val == root.right.val + 1)
                    maxVal = Math.max(maxVal, 1 + lval[1] + rval[0]);                
            }
            maxVal = Math.max(maxVal, Math.max(toRet[0], toRet[1]));
            //System.out.println(root.val + ":" + toRet[0] + ":" + toRet[1]);
            return toRet;
        }

Log in to reply
 

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