边工作边刷题:70天一遍leetcode: day 89

Binary Tree Longest Consecutive Sequence
简单题,只要单向递增的
错误点:

  • +1,不是>=
  • 注意是top.left, top.right, 不是root.left, root.right:debug log:打印每层root.val和当前curlen

https://repl.it/Ccr6/3 (iteration: pre-order traversal)
https://repl.it/Ccr6/4 (recursion)

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

# For example,
#   1
#     
#      3
#     / 
#   2   4
#         
#          5
# Longest consecutive sequence path is 3-4-5, so return 3.
#   2
#     
#      3
#     / 
#   2    
#   / 
#  1
# Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

from collections import deque

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


class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        stk = deque([(root,1)])
        maxLen = 0
        while stk:
            top, curlen = stk.pop()
            maxLen = max(curlen, maxLen)

            if top.left:
                stk.append((top.left, curlen+1 if top.left.val==top.val+1 else 1)) # error: root.left
            
            if top.right:
                stk.append((top.right, curlen+1 if top.right.val==top.val+1 else 1))
        
        return maxLen
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        
        def dfs(root, pre, curLen):
            if root.val==pre+1: # +1, not >= 
                curLen+=1
            else:
                curLen=1

            self.maxLen=max(self.maxLen, curLen)
            if root.left:
                dfs(root.left, root.val, curLen)
            
            if root.right:
                dfs(root.right, root.val, curLen)
        
        self.maxLen = 0
        if not root: return 0
        dfs(root, float('-inf'), 0)
        return self.maxLen
原文地址:https://www.cnblogs.com/absolute/p/5815812.html