[LeetCode][Python3] 617. Merge Two Binary Trees
2018. 10. 8. 01:15 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/merge-two-binary-trees/description/
My 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 mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
else:
t1 = t1 or t2
return t1
Comment :
새로운 Tree를 만들지 않고 그냥 recursion 하면서 t1에다 val이나 reference를 update 치는 방식으로 구현하였다.
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 118. Pascal's Triangle (0) | 2018.10.17 |
---|---|
[LeetCode][Python3] 125. Valid Palindrome (0) | 2018.10.17 |
[LeetCode][Python3] 66. Plus One (0) | 2018.10.15 |
[LeetCode][Python3] 543. Diameter of Binary Tree (0) | 2018.10.09 |
[LeetCode][Python3] 581. Shortest Unsorted Continuous Subarray (0) | 2018.10.08 |
[LeetCode][Python3] 572. Subtree of Another Tree (0) | 2018.10.07 |
[LeetCode][Python3] 538. Convert BST to Greater Tree (0) | 2018.10.07 |
[LeetCode][Python3] 438. Find All Anagrams in a String (0) | 2018.10.07 |
최근에 달린 댓글 최근에 달린 댓글