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;

 

posted @ 2019-06-26 21:44  起点菜鸟  阅读(225)  评论(0编辑  收藏  举报