描述
中文English
给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序
)。
您在真实的面试中是否遇到过这个题? 是
题目纠错
样例
样例1:
输入:
{1,#,3,2,4,#,#,#,5}
输出:3
说明:
这棵树如图所示
1
\
3
/ \
2 4
\
5
最长连续序列是3-4-5,所以返回3.
样例2:
输入:
{2,#,3,2,#,1,#}
输出:2
说明:
这棵树如图所示:
2
\
3
/
2
/
1
最长连续序列是2-3,而不是3-2-1,所以返回2.
class Solution:
"""
@param root: the root of binary tree
@return: the length of the longest consecutive sequence path
"""
def longestConsecutive(self, root):
# write your code here
if root == None:
return
self.helper(root, root.val + 1, 0)
return self.count + 1
def helper(self, root, target, count):
print(target)