題目地址:
https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/description
給定一棵二叉樹,求所有從上向下的路徑中,數值連續(意思是)並且長度最長的那條路徑,只需返回路徑長度。
思路是DFS,在DFS的同時返回以root爲出發點的最長路徑的長度,然後時刻更新全局最長長度變量。代碼如下:
public class Solution {
// 記錄已經找到的連續最長路徑的長度
private int res;
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
// write your code here
res = 0;
dfs(root);
return res;
}
// 對root爲根的樹進行DFS,並且返回以root爲出發點得到的最長路徑長度
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
// len表示從root出發得到的最長路徑長度,先初始化爲1
int len = 1;
// 得到以左子樹根爲出發點的最長路徑長度,和右子樹根爲出發點的最長路徑長度
int left = dfs(root.left), right = dfs(root.right);
// 如果左子樹非空並且當前節點能接在左子樹路徑之前,則更新len
if (root.left != null && root.left.val - root.val == 1) {
len = Math.max(len, 1 + left);
}
if (root.right != null && root.right.val - root.val == 1) {
len = Math.max(len, 1 + right);
}
// 更新全局變量res
res = Math.max(res, len);
return len;
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
時間複雜度,空間。