LeetCode-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.

 

翻譯:

給定兩個二叉樹並且想象當你用一個去覆蓋另一個的時候,兩棵樹的有些節點會重疊而有些卻不會。

你需要將它們合併成一棵新的二叉樹。合併的規則是如果兩個節點重疊,那麼將兩個節點的值相加作爲合併後的節點的新值。否則,不爲空的節點講座爲新樹的節點。

例子 1:

輸入: 
	樹 1                     樹 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
輸出: 
合併後的樹:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

注意: 合併過程必須從兩個樹的根節點開始。

 

思路:

用遞歸來解決,若一棵樹的節點爲空,則返回另一棵樹的節點作爲合併後的新節點;若兩棵樹的節點都不爲空,則新節點的值爲兩棵樹的節點值的和。

 

C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
using namespace std;

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 (t2 == NULL)
			return t1;
		if (t1 == NULL)
			return t2;
		TreeNode* t=new TreeNode(t1->val + t2->val);
		t->left = mergeTrees(t1->left, t2->left);
		t->right = mergeTrees(t1->right, t2->right);
		return t;
	}
};

void TreePrint(TreeNode* node) {
	if(node != NULL) {
		cout << node->val << " ";
		TreePrint(node->left);
		TreePrint(node->right);
	}
}

int main()
{
	Solution s;
	TreeNode* root1 = new TreeNode(1);
	root1->left = new TreeNode(3);
	root1->right = new TreeNode(2);
	root1->left->left = new TreeNode(5);

	TreeNode* root2 = new TreeNode(2);
	root2->left = new TreeNode(1);
	root2->right = new TreeNode(3);
	root2->left->right = new TreeNode(4);
	root2->right->right = new TreeNode(7);
	TreeNode* result = s.mergeTrees(root1, root2);
	TreePrint(result);
    return 0;
}

 

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