スポンサーリンク

【LeetCode】617. Merge Two Binary Trees 解答・解説【Python】

スポンサーリンク
スポンサーリンク
この記事は約3分で読めます。

 

問題

原文

You are given two binary trees root1 and root2.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

 

Example 1:

Example 2:

 

Constraints:

  • The number of nodes in both trees is in the range [0, 2000].
  • -104 <= Node.val <= 104

 

内容

2つの二分木root1,root2が与えられます。

片方の木をもう片方の木に被せると、いくつかのノードは重なり、残りは重なりません。

二つの木を新しい二分木に結合してください。

結合ルールは、もし二つのノードが重なればそのノードの値を合計し新しいノードの値とします。

二つのノードが重ならない場合は、NOT nullノードが新しい木のノードとして使用されます。

結合後の木を返してください。

 

 

・補足

2つの木を重ねたときに、3つのパターンがあります。

➀2つともノードがある場合

②片方だけノードがある場合

③2つともノードがない場合

 

➀はノードの値を合計する

②は片方のノードの値をそのまま使う

③は何もしない

 

 

※正しくない可能性があります。

 

解答

解答1:Python,再帰(recursion)

 

 

 

 

解答2:

 

 

 

補足・参考・感想

参考

 

 

前:695. Max Area of Island

次:77. Combinations

LeetCode 解答・解説記事一覧

コメント