Leetcode-549. Binary Tree Longest Consecutive Sequence II

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. 

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:

Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].

Example 2:

Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].
这个题目还是蛮简单的,有一个需要注意的地方就是必须是连续值。

public class Solution {
    private int max = 1;
    public int longestConsecutive(TreeNode root) {
        if(root == null) return 0;
        help(root);
        
        return max;
    }
    
    public int[] help(TreeNode root){
        if(root == null) return null;
        int[] right = help(root.right);
        int[] left = help(root.left);
        int[] result = new int[]{1,1};
        if(right == null && left == null) return result;
    
        if(root.right != null){
            if(root.val == root.right.val + 1) {
                max = Math.max(max, right[0] + 1);
                result[0] = right[0] + 1;
                result[1] = 1;
            }else if(root.val == root.right.val - 1){
                max = Math.max(max, right[1] + 1);
                result[0] = 1;
                result[1] = right[1] + 1;
            }
        }
        if(root.left != null){
            if(root.val == root.left.val + 1) {
                max = Math.max(max, left[0] + result[1]);
                result[0] = Math.max(result[0], left[0] + 1);
            }else if(root.val == root.left.val - 1){
                max = Math.max(max, left[1] + result[0]);
                result[1] = Math.max(result[1], left[1] + 1); 
            }
        }
    
        return result;
    }
}




你可能感兴趣的:(算法)