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:

Input: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

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


給定兩顆二叉樹,歸併兩棵樹:將相同位置的結點的值加起來爲新結點,並最終返回新的二叉樹的根節點。

簡單的思路是,從根節點開始,遍歷兩顆樹的相同位置的每一個節點,判斷樹的結點是否爲空,來決定是否要生成新結點以及確定結點的值。如果在該位置上,兩個結點都爲空,則不生成新結點;否則,生成新結點,並根據具體情況決定結點的值。利用遞歸:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (!t1 && !t2)
            return nullptr;
        int value1 = t1 ? t1->val : 0;
        int value2 = t2 ? t2->val : 0;
        TreeNode* root = new TreeNode(value1 + value2);
        
        root->left = mergeTrees(t1 ? t1->left : nullptr, t2 ? t2->left : nullptr);
        root->right = mergeTrees(t1 ? t1->right : nullptr, t2 ? t2->right : nullptr);
        return root;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章