549. 二叉树中最长的连续序列

 

 

class Solution {
    public int longestConsecutive(TreeNode root) {
        dfs(root);
        return res;
    }
    private int res = 0;
    public int[] dfs(TreeNode root) { // 以root开始, path[0]:root为增位置的最长路径 path[1]:root为减位置的最长路径      
        int[] path = new int[]{1,1};
        if(root == null) return null; // return什么没关系,左右子树为null不参与判断

        int[] left = dfs(root.left); 
        int[] right = dfs(root.right); 

        if(root.left != null) {
            if(root.left.val - root.val == 1) { // 递减
                path[1] += left[1];
            }
            if(root.left.val - root.val == -1) {
                path[0] += left[0];
            }
        }
        if(root.right != null) {
            if(root.right.val - root.val == 1) {
                path[1] = Math.max(path[1],right[1]+1);
            } 
            if(root.right.val - root.val == -1) {
                path[0] = Math.max(path[0],right[0]+1);
            }
        }
        res = Math.max(res,path[0]+path[1]-1);
        return path;
    }
}

 

posted @ 2020-07-14 17:38  Sexyomaru  阅读(350)  评论(0编辑  收藏  举报