Hello_Motty

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

题意:将两个二叉树合并。假如以左侧树为基础,如果左侧树上有同一节点则加上右侧树上相应节点,左侧树上没有相应节点右侧树上有相应节点就补充此节点,左右树上都没有的节点就仍然为空。要求从根节点开始。

基本思路:

同时遍历两棵树,并把右侧树上的val不停加在左侧树上。最直观的方法就是递归遍历,顺序上可以使用先序遍历或者层序遍历。

代码如下(先序遍历):

1 struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2) {
2     if(!t1) return t2;
3     if(!t2) return t1;
4     t1->val += t2->val;
5     t1->left = mergeTrees(t1->left,t2->left);
6     t1->right = mergeTrees(t1->right, t2->right);
7     return t1;
8 }

其实这个题考察的就是二叉树的先序遍历和层序遍历,只不过从一棵树变成了两棵树。

当然也可以新建一棵树,将新节点全部添加到新树上,最后返回新树。

c++的代码如下:

 1 class Solution {
 2 public:
 3     TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
 4         if (!t1 && !t2) {
 5             return nullptr;
 6         }
 7         TreeNode* root = new TreeNode((t1 ? t1->val : 0) + (t2 ? t2->val : 0));
 8         root->left = mergeTrees((t1 ? t1->left : nullptr), (t2 ? t2->left : nullptr));
 9         root->right = mergeTrees((t1 ? t1->right : nullptr), (t2 ? t2->right : nullptr));
10         return root;
11     }
12 };

简单题不需要太多的花式解法。另外层序遍历需要引入队列进行保存所以在此题中可以不必使用。

posted on 2017-08-10 22:02  Hello_Motty  阅读(241)  评论(0编辑  收藏  举报