LeetCode – 617. Merge Two Binary Trees

題目來源:LeetCode -617. Merge Two Binary Trees


題目:

Given two binary trees and 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 them 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 new tree.

Example 1:

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

 

粗略翻譯:

題目會給兩組二元樹,程式目的是要將兩顆二元樹合併

如果樹的節點有重疊,則將節點的值相加

如果沒有重疊,則新增節點到對應位置

解法:

很基本的解法,先檢查兩顆樹的節點是否為null

如果有一個非null,則新增一節點並將兩節點的值相加

而left跟right的節點則是再一次的執行該方法,

並將兩節點的對應位置當參數傳遞


網站:http://wp.mlab.tw/
GitHub:https://github.com/yoll522/LeetCode
程式碼:https://github.com/yoll522/LeetCode/tree/master/338.%20Counting%20Bits

One comment

Leave a Reply

你的電子郵件位址並不會被公開。 必要欄位標記為 *