码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 549. Binary Tree Longest Consecutive Sequence II

时间:2019-06-26 22:05:41      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:ali   https   des   values   bsp   red   seq   length   return   

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

标签:ali   https   des   values   bsp   red   seq   length   return   

原文地址:https://www.cnblogs.com/rookielet/p/11094087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!