1. 程式人生 > 實用技巧 >549. 二叉樹中最長的連續序列

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; } }