来自:leecode
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1==nullptr)
return t2;
if(t2==nullptr)
return t1;
//同时先序遍历两个二叉树
stack<TreeNode*> stack1;
stack<TreeNode*> stack2;
//根节点入栈
stack1.push(t1);
stack2.push(t2);
while (!stack1.empty())
{
//节点出栈
if(stack2.empty()) return t1;
TreeNode* ta=stack1.top();
stack1.pop();
TreeNode* tb=stack2.top();
stack2.pop();
//先序遍历根
//val相加
ta->val+=tb->val;
//先序遍历左子树
if(ta->left==nullptr) {ta->left=tb->left;}
else {
stack1.push(ta->left);
stack2.push(tb->left);
}
//先序遍历右子树
if(ta->right==nullptr) {ta->right=tb->right;}
else {
stack1.push(ta->right);
stack2.push(tb->right);
}
}
return t1;
}