题目地址:
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)。