Share my java solution (mandarin comment), pretty obvious dfs...


  • 0
    M
    public class Solution {
        
        int maxLen = 0;
        
        public int longestConsecutive(TreeNode root) {
            dfs(root);
            return maxLen;
        }
        
        private int dfs(TreeNode root) {
            if (root == null) { return 0; }
            int left = dfs(root.left);
            int right = dfs(root.right);
            int curLeft = root.left!=null&&root.val==root.left.val-1 ? left+1 : 1;  // 左面能和root.val接上 vs. 接不上
            int curRight = root.right!=null&&root.val==root.right.val-1 ? right+1 : 1;  // 右面能和root.val接上 vs. 接不上
            int curMax = Math.max(curLeft, curRight);
            maxLen = Math.max(maxLen, curMax);  // 更新global max
            return curMax;  // 向上一层报告当前最长链的长度
        }
    }

Log in to reply
 

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