原题地址:https://leetcode.com/problems/merge-two-binary-trees/description/
题目描述
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.
题目大意是,给出两棵二叉树,将其合并成一棵。具体的要求是,如果在某一位置有重叠的节点,则把节点的值相加;如果在某一位置只有一个节点,则取那个节点;若在某一位置都没有节点,则合并出的树的相同位置也没有节点。
思路
同步遍历两棵二叉树,因为节点的结构体里没有指向父节点的指针,所以必须根据它们子节点的情况再决定进行什么样的操作。
代码
/**
* 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:
void travelTogether(TreeNode* a,TreeNode* b){
if(a==NULL && b==NULL){
return;
}
if(a!=NULL && b!=NULL){
a->val+=b->val;
}
if(a==NULL && b!=NULL){
//pass
}
if(a!=NULL && b==NULL){
//pass
}
if(a->left!=NULL && b->left!=NULL){
travelTogether(a->left,b->left);
}else if(a->left!=NULL && b->left ==NULL){
}else if(a->left==NULL && b->left!=NULL){
a->left=b->left;
}else{ // a->left==NULL && b->left==NULL
//pass
}
if(a->right!=NULL && b->right!=NULL){
travelTogether(a->right,b->right);
}else if(a->right!=NULL && b->right ==NULL){
}else if(a->right==NULL && b->right!=NULL){
a->right=b->right;
}else{ // a->right==NULL && b->right==NULL
//pass
}
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1==NULL){
return t2;
}
if(t2==NULL){
return t1;
}
travelTogether(t1,t2);
return t1;
}
};
虽然是Easy
的题但是觉得写起来很别扭,也只比24%
左右的人更优