题目:
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
1
\
3
/ \
2 4
\
5
Longest consecutive sequence path is 3-4-5,
so return 3.
2
\
3
/
2
/
1
Longest consecutive sequence path is 2-3,not3-2-1,
so return 2.思路:
由于树上的全局最长长度可能和其root没有任何关系(有可能其最长长度对应的起点是root的孩子的孩子。。。),所以我们必须同时记录一个全局最大长度和一个局部最大长度。每次递归的时候更新局部最大长度,一旦发现局部最大长度超过了全局最大长度,则更新全局最大长度。具体实现可以采用DFS。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestConsecutive(TreeNode* root) {
if(root == NULL) {
return 0;
}
int global_max = 0;
dfs(root, global_max, root->val - 1, 0);
return global_max;
}
private:
void dfs(TreeNode* root, int &global_max, int pre_value, int local_max) {
if(root == NULL) {
return;
}
int len = 1;
if(root->val == pre_value + 1) {
len = local_max + 1;
}
global_max = max(global_max, len);
dfs(root->left, global_max, root->val, len);
dfs(root->right, global_max, root->val, len);
}
};
本文探讨了如何在二叉树中寻找最长连续序列路径的问题,并通过深度优先搜索(DFS)的方法来解决这一挑战。文章提供了详细的算法思路及C++实现代码。
812

被折叠的 条评论
为什么被折叠?



