【Lintcode】619. Binary Tree Longest Consecutive Sequence III

题目地址:

https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence-iii/description

给定一个多叉树,返回其从任意节点到任意节点的连续上升路径(指形如 x , x + 1 , x + 2 , . . . x,x+1,x+2,... x,x+1,x+2,...的路径)的长度的最大值。

思路是DFS。由于任意路径都有最高节点,我们可以按照这个将路径分类。当DFS到一个节点的时候,就去计算其向下的连续上升路径长度和连续下降路径长度然后返回给上层,这可以递归的来计算,计算左右子树的结果然后看看能否拼到当前节点上。DFS的同时更新答案即可。代码如下:

import java.util.List;

public class Solution {
    
    private int res;
    
    /**
     * @param root the root of k-ary tree
     * @return the length of the longest consecutive sequence path
     */
    public int longestConsecutive3(MultiTreeNode root) {
        // Write your code here
        dfs(root);
        return res;
    }
    
    private int[] dfs(MultiTreeNode cur) {
        if (cur == null) {
            return null;
        }
        
        // incLen存从当前节点向下的最长上升路径的长度;decLen存从当前节点向下的最长下降路径的长度
        int incLen = 1, decLen = 1;
        for (MultiTreeNode child : cur.children) {
            if (child != null) {
                int[] len = dfs(child);
                if (child.val == cur.val + 1) {
                    incLen = Math.max(incLen, 1 + len[0]);
                }
                if (child.val == cur.val - 1) {
                    decLen = Math.max(decLen, 1 + len[1]);
                }
            }
        }
        
        // 更新答案
        res = Math.max(res, incLen + decLen - 1);
        
        return new int[]{incLen, decLen};
    }
}

class MultiTreeNode {
    int val;
    List<MultiTreeNode> children;
    
    public MultiTreeNode(int val) {
        this.val = val;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值