[LeetCode] 298. Binary Tree Longest Consecutive Sequence_Medium tag: DFS recursive

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).

Example 1:

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 3

Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:

   2
    \
     3
    / 
   2    
  / 
 1

Output: 2 

Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

这个题目思路跟[LeetCode] 687. Longest Univalue Path_Easy tag: DFS recursive, 但实际上比它还简单, 因为不需要验证l + root + r, 但是也只是self.ans 里面少加一个判断而已, 本质一样, 用helper function, 得到包括root 的最大的increasing consecutive path 的 number of nodes, 并且每次跟self.ans 比较, 最后return self.ans.

 

1. Constraints

1) empty => 0

2) element will be intergeres

 

2) Ideas

DFS    T; O(n)    S: O(n)

 

3) code

 1 class Solution:
 2     def longestConsecutive(self, root):
 3         self.ans = 0
 4         def helper(root):
 5             if not root: return 0
 6             l, r = helper(root.left), helper(root.right)
 7             l = l if l != 0 and root.val + 1 == root.left.val else 0
 8             r = r if r != 0 and root.val + 1 == root.right.val else 0
 9             self.ans = max(self.ans, max(l, r) + 1)
10             return max(l, r) + 1
11         helper(root)
12         return self.ans

 

4. Test cases

   1
    \
     3
    / \
   2   4
        \
         5

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9327067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值