题目地址:
https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence-ii/description
给定一个二叉树,要求返回从树中任意节点到任意节点的数字连续上升的路径(形如 x , x + 1 , x + 2 x,x+1,x+2 x,x+1,x+2这种)中,最长的长度。
思路是DFS。由于任何一条路径都有高度最高的节点,我们就按照这个来分类。在DFS的时候返回从当前节点向下的连续上升路径和连续下降路径的长度,这可以通过递归求解左右子树来完成,接着用长度为 2 2 2的数组来返回,如果树空返回null。拿到左右子树树根的信息后,再判断一下左右子树树根能否被接到当前节点上,然后更新答案,并往上返回结果即可。代码如下:
public class Solution {
private int res;
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
public int longestConsecutive2(TreeNode root) {
// write your code here
dfs(root);
return res;
}
// 返回长度为2的数组,第0位表示从cur向下的最长递增路径的长度,
// 第1位表示从cur向下的最长递减路径的长度
private int[] dfs(TreeNode cur) {
if (cur == null) {
return null;
}
int[] left = dfs(cur.left), right = dfs(cur.right);
int upLen = 1, downLen = 1;
// 如果左子树不为空,则判断一下能否接到当前节点上
if (left != null) {
if (cur.left.val == cur.val + 1) {
upLen = Math.max(upLen, 1 + left[0]);
}
if (cur.left.val == cur.val - 1) {
downLen = Math.max(downLen, 1 + left[1]);
}
}
// 如果右子树不为空,则判断一下能否接到当前节点上
if (right != null) {
if (cur.right.val == cur.val + 1) {
upLen = Math.max(upLen, 1 + right[0]);
}
if (cur.right.val == cur.val - 1) {
downLen = Math.max(downLen, 1 + right[1]);
}
}
// 更新答案
res = Math.max(res, upLen + downLen - 1);
// 将本节点的结果向上返回
return new int[]{upLen, downLen};
}
}
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。