Skip to content

Latest commit

 

History

History
91 lines (64 loc) · 1.94 KB

298. Binary-Tree-Longest-Consecutive-Sequence.md

File metadata and controls

91 lines (64 loc) · 1.94 KB

Description

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.

python solution

要找到连续增长的序列,肯定是要递归遍历树。在遍历的过程中,不断记录当前最长的序列长度。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def __init__(self):
        self.res = 1

    def traversal(self, root, length):
        self.res = max(self.res, length) # 每次遇到新的节点都要更新一下结果。
        if not root: return
        if root.left:
            if root.left.val == root.val + 1: # 如果子节点值等于当前节点值加1,将序列长度加1。
                self.traversal(root.left, length + 1)
            else: # 如果子节点值不等于当前节点值加1,直接将length重置为1
                self.traversal(root.left, 1)
        if root.right:
            if root.right.val == root.val + 1:
                self.traversal(root.right, length + 1)
            else:
                self.traversal(root.right, 1)

    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0  # 特殊情况处理
        self.traversal(root, 1) # 默认初始长度为1
        return self.res