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).
using recursive is easier.
public class Solution {
int max = 0;
public:
int longestConsecutive(TreeNode* root) {
if(!root) return 0;
helper(root,0,root.val);
return max;
}
private:
void helper(TreeNode* root,int cur, int target){
if(root) return;
if(root->val==target) cur++;
else cur=1;
max = max(cur, max);
helper(root->left, cur, root->val+1);
helper(root->right, cur, root->val+1);
}
}

本文介绍了一种寻找二叉树中最长连续路径的方法。该路径需从父节点指向子节点,并通过递归实现。代码示例使用C++编写。
391

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



