617. Merge Two Binary Trees

本文详细解析了二叉树合并算法,通过递归方式实现两棵二叉树的节点值叠加,对于相同位置的节点,其值相加;对于不同位置的节点,保留非空节点。文章提供了C++代码实现,并附有示例说明。

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

1.问题描述

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.
[来自 <https://leetcode.com/problems/merge-two-binary-trees/description/>](%E6%9D%A5%E8%87%AA%20%3Chttps://leetcode.com/problems/merge-two-binary-trees/description/%3E) 

2.问题分析

将两个二叉树进行合并,两树中同一位置都存在节点,则将两个节点值叠加,同一位置的不存在节点的,则将另一个树的节点添加到该位置,否则保留原来节点。
对这个问题,首先想到的是用什么样的方法同时遍历两个树,才能保证每次到达的节点序号一样。最能想到的是利用层序遍历,一层层来,但是对于空结点无能为力,层序遍历并不能识别空结点,人为假如空结点比较繁琐。往递归的方向思考,归纳出共性:
1.父节点都存在,则
父结点相叠加,
若其同侧叶子节点均存在,则递归调用,
若目地二叉树儿子节点不存在,则把源二叉树的儿子节点连接过来
2.目的二叉树父节点不存在,则
将当前源父节点赋给目的父结点

3.c++代码

//我的代码:(beats 95%)
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) 
{
	if (t1 != NULL&&t2 != NULL)
	{
		t1->val += t2->val;
		if (t1->left != NULL&&t2->left != NULL)
		{
			mergeTrees(t1->left, t2->left);
		}
		else if (t1->left == NULL&&t2->left != NULL)
			t1->left = t2->left;

		if (t1->right != NULL&&t2->right != NULL)
		{
			mergeTrees(t1->right, t2->right);
		}
		else if (t1->right == NULL&&t2->right != NULL)
		{
			t1->right = t2->right;
		}
	}
	else if (t1 == NULL)
		t1 = t2;
	return t1; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值