[617]Merge Two Binary Trees

本文介绍了一种将两棵二叉树合并为一棵新二叉树的算法,合并规则为当两个节点重叠时,将节点值相加作为新节点值;若节点不重叠,则使用非空节点作为新树节点。文章通过层次遍历的方法实现该算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路:层次遍历,往队列里每次塞进去两棵树相同位置上不为空的节点,因为最终输出的是左树,则节点一共有以下3种情况:

1.左右树对应位置上孩子只有左树为空,则把右树孩子赋给左树对应位置

2.左右树对应位置上孩子都不为空,直接塞进队列里就可以了,出队列时累加起来给左树

3.左右树对应位置上孩子只有右树为空,则不需要处理,我们需要输出的是左边的树(X)

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution 
11 {
12 public:
13     TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) 
14     {
15         if(t1 == nullptr) return t2;
16         if(t2 == nullptr) return t1;
17         if(t1 == nullptr && t2 == nullptr) return nullptr;
18         else
19         {
20           queue<TreeNode*>q;
21           q.push(t1);
22           q.push(t2);
23           while(!q.empty())
24           {
25             TreeNode* l1 = q.front();
26             q.pop();
27             TreeNode* l2 = q.front();
28             q.pop();
29             l1->val +=l2->val;
30             if(l1->left != nullptr && l2->left!=nullptr)
31             {
32               q.push(l1->left);
33               q.push(l2->left);
34             }
35             if(l1->right != nullptr && l2->right!=nullptr)
36             {
37               q.push(l1->right);
38               q.push(l2->right);
39             }
40             if(l1->left == nullptr && l2->left != nullptr )
41             {
42               l1->left = l2->left;
43             }
44             if(l1->right == nullptr && l2->right != nullptr)
45             {
46               l1->right = l2->right;
47             }
48           }
49           return t1;
50         }
51     }
52 };

转载于:https://www.cnblogs.com/Swetchine/p/11247895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值