(先码,代码是看别人的,还有地方有点迷糊)
描述:
给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序
)。
样例:
例1:
输入:
1
\
3
/ \
2 4
\
5
输出:3
解释:
Longest consecutive sequence path is 3-4-5, so return 3.
例2:
输入:
2
\
3
/
2
/
1
输出:2
解释:
Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.
代码:
public:
int longestConsecutive(TreeNode* root) {
return helper(root, NULL, 0);
}
int helper(TreeNode *root, TreeNode *p, int res) {
if (!root) return res;
res = (p && root->val == p->val + 1) ? res + 1 : 1;
return max(res, max(helper(root->left, root, res), helper(root->right, root, res)));
}