https://leetcode.com/problems/merge-two-binary-trees/
Merge Two Binary Trees - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
두 개의 이진트리의 값을 더해서 합친 이진트리를 반환하는 문제이다.
재귀를 사용해 이진 트리의 모든 노드를 순회하면서 합쳐 새로운 이진 트리를 만들어 반환하게끔 하였다.
소스 코드
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if root1 and root2:
node = TreeNode(root1.val + root2.val)
node.left = self.mergeTrees(root1.left, root2.left)
node.right = self.mergeTrees(root1.right, root2.right)
return node
else:
return root1 or root2
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 110. Balanced Binary Tree [Python] (0) | 2022.09.02 |
---|---|
LeetCode - 297. Serialize and Deserialize Binary Tree [Python] (0) | 2022.08.31 |
LeetCode - 226. Invert Binary Tree [Python] (0) | 2022.08.29 |
LeetCode - 687. Longest Univalue Path [Python] (0) | 2022.08.29 |
LeetCode - 543. Diameter of Binary Tree [Python] (0) | 2022.08.28 |