Straightforward DFS with Python


  • 0

    When we hear "longest path" in "binary tree", DFS is very attractive.

    class Solution(object):
        def longestConsecutive(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root is None:
                return 0
            return self.__longest(root, None, 0) + 1
            
        def __longest(self, root, parent, count):
            if parent is not None:
                if root.val - parent.val == 1:
                    count += 1
                else:
                    count = 0
            countLeft = 0
            countRight = 0
            if root.left is not None:
                countLeft = self.__longest(root.left, root, count)
            if root.right is not None:
                countRight = self.__longest(root.right, root, count)
            return max(count, countLeft, countRight)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.