Share my Python code


  • 1
    X
    # 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
            # if not root.right and not root.left:
            #     return 1
            return self.dfs(root, 0)
            
        def dfs(self, root, auc):
            if not root:
                return auc
            if not root.left and not root.right:
                return auc + 1
            leftlength, rightlength = 0,0
            if root.left:
                if root.left.val == root.val + 1:
                    leftlength = self.dfs(root.left, auc + 1)
                else:
                    leftlength = self.dfs(root.left, 0)
            if root.right:
                if root.right.val == root.val + 1:
                    rightlength = self.dfs(root.right, auc + 1)
                else:
                    rightlength = self.dfs(root.right, 0)
            return max(leftlength, rightlength, auc+1)

Log in to reply
 

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