6 lines python with getattr


  • 0
    Q
    class Solution(object):
        def mergeTrees(self, t1, t2):
            """
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            """
            if t1 is None and t2 is None:
                return None
            root = TreeNode(getattr(t1, 'val', 0) + getattr(t2, 'val', 0))
            root.left = self.mergeTrees(getattr(t1, 'left', None), getattr(t2, 'left', None))
            root.right = self.mergeTrees(getattr(t1, 'right', None), getattr(t2, 'right', None))
            return root
    

  • 0

    It's cool to use getattr but actually you can just use like t1 and t1.left to do the same thing.


Log in to reply
 

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