LeetCode 549. Binary Tree Longest Consecutive Sequence II

Posted rookielet

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 549. Binary Tree Longest Consecutive Sequence II相关的知识,希望对你有一定的参考价值。

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.

链接:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/

Note: All the values of tree nodes are in the range of [-1e7, 1e7].

题解:

此题是一道典型的递归问题,需要一个递归函数来返回两个量:从该节点出发最长的递增路径和最长的递减路径。而某个节点的最长连续序列的长度就是最长递增路径和最长递减路径的和的基础上减1。因为要返回两个量,我选择返回一个长度为2的数组。

代码如下:

int res;
    public int longestConsecutive(TreeNode root) 
        if(root == null) return 0;
        res = 0;
        helper(root);
        return res - 1;
    
    private int[] helper(TreeNode root) 
        if(root == null) return new int[2];
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        int inc = 1, dec = 1;
        int[] ret = new int[]0, 0;
        if(root.left != null) 
            if(root.left.val == root.val - 1) 
                ret[0] = left[0];
             else if(root.left.val == root.val + 1) 
                ret[1] = left[1]; 
            
        
        if(root.right != null) 
            if(root.right.val == root.val - 1) 
                ret[0] = Math.max(ret[0], right[0]);
             else if(root.right.val == root.val + 1) 
                ret[1] = Math.max(ret[1], right[1]);
            
        
        
        ret[0]++;
        ret[1]++;
        // System.out.println(root.val + ": " + ret[0] + ", " + ret[1]);
        res = Math.max(ret[0] + ret[1], res);
        return ret;

 

以上是关于LeetCode 549. Binary Tree Longest Consecutive Sequence II的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Binary tree-- 606. Construct String from Binary Tree

[Leetcode] Binary search tree --Binary Search Tree Iterator

Leetcode[110]-Balanced Binary Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

LeetCode 110. Balanced Binary Tree 递归求解