题解 | #合并二叉树#
合并二叉树
http://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
按照t1先序遍历
若t1和t2都不为空,那么t1和t2的val相加,递归help(t1->left,t2->left)和help(t1->right,t2->right)
若t1为空,t2不为空,令t1=t2
若t1不为空,t2为空,不用操作
若t1、t2都为空,直接返回即可
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
void help(TreeNode* &t1,TreeNode* t2){
if(t1==NULL&&t2==NULL) return ;
else if(t1==NULL&&t2!=NULL) t1=t2;
else if(t1!=NULL&&t2!=NULL) t1->val+=t2->val,help(t1->left,t2->left),help(t1->right,t2->right);
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
// write code here
help(t1,t2);
return t1;
}
};