# leetcode 617. 合并二叉树 思考分析

## 思路1：递归遍历两棵树，构造一棵新的树

1、递归参数以及返回值

2、终止条件

3、逻辑（这里直接贴代码和遇到的问题）

traversal(t1->left,t2->left);：必须要保证t1、t2都不为空，否则编译器会报错。
member access within null pointer of type 'TreeNode'

/**
* 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:
TreeNode* traversal(TreeNode* t1, TreeNode* t2)
{
if(t1 == NULL && t2 == NULL) return NULL;
int rootVal=0;
if(t1 ==NULL && t2!=NULL)
{
rootVal = t2->val;
TreeNode* NewRoot = new TreeNode(rootVal);
NewRoot->left = t2->left;
NewRoot->right = t2->right;
return NewRoot;
}
else if(t1 !=NULL && t2==NULL)
{
rootVal = t1->val;
TreeNode* NewRoot = new TreeNode(rootVal);
NewRoot->left = t1->left;
NewRoot->right = t1->right;
return NewRoot;
}
else
{
rootVal = t1->val + t2->val;
TreeNode* NewRoot = new TreeNode(rootVal);
NewRoot->left = traversal(t1->left,t2->left);
NewRoot->right = traversal(t1->right,t2->right);
return NewRoot;
}
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
return traversal(t1,t2);
}
};


## 思路2：层序遍历两棵树，构造一棵新的树

LeetCode 101. 对称二叉树 思考分析中，有过利用队列同时遍历两棵树的经历，这里回顾了一下，然后直接上。

class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == NULL && t2==NULL) return NULL;
else if(t1 == NULL && t2!=NULL) return t2;
else if(t1 != NULL && t2==NULL) return t1;
queue<TreeNode*> que;
que.push(t1);
que.push(t2);
while(!que.empty())
{
TreeNode* T1Node = que.front();
que.pop();
TreeNode* T2Node = que.front();
que.pop();
//此时两个结点一定不为空
T1Node->val += T2Node->val;
//如果两棵树左结点都不为空，加入队列
if(T1Node->left && T2Node->left)
{
que.push(T1Node->left);
que.push(T2Node->left);
}
//如果两棵树右结点都不为空，加入队列
if(T1Node->right && T2Node->right)
{
que.push(T1Node->right);
que.push(T2Node->right);
}
//当t1的某个结点为空时且t2的结点不为空，不入队列
//当t1左结点为空，t2左结点不为空
if(!T1Node->left && T2Node->left)
{
T1Node->left = T2Node->left;
}
if(!T1Node->right && T2Node->right)
{
T1Node->right = T2Node->right;
}
}
return  t1;
}
};

05-02 138
09-06 5万+

08-30 59
03-07 370
11-29 30