背景是合并两颗二叉树
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fe6adda37d964aa3788b92b44dc52f7a.png)
相关代码
#include <iostream>
using namespace std;
#define MaxSize 15
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x = 0) : val(x), left(NULL), right(NULL) {}
};
struct SqQueue {
TreeNode data[MaxSize];
int front, rear;
};
SqQueue Q;
void InitQueue(SqQueue &Q) {
Q.rear = Q.front = 0;
}
bool isEmpty(SqQueue Q) {
if (Q.front == Q.rear) return true;
else return false;
}
bool EnQueue(SqQueue &Q, TreeNode x) {
if ((Q.rear + 1) % MaxSize == Q.front) return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue &Q, TreeNode &x) {
if (Q.rear == Q.front) return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
void Visit(TreeNode *T) {
cout << T->val << " ";
}
void LevelOrder(TreeNode *T) {
InitQueue(Q);
TreeNode p;
EnQueue(Q, *T);
while (!isEmpty(Q)) {
DeQueue(Q, p);
Visit(&p);
if (p.left != NULL)
EnQueue(Q, *p.left);
if (p.right != NULL)
EnQueue(Q, *p.right);
}
}
TreeNode *Merge(TreeNode *t1, TreeNode *t2) {
if (t1 && t2) {
t1->val = t1->val + t2->val;
if (t1->left) {
Merge(t1->left, t2->left);
} else {
t1->left = t2->left;
}
if (t1->right) {
Merge(t1->right, t2->right);
} else {
t1->right = t2->right;
}
} else {
if (t2) {
return t2;
} else {
return t1;
}
}
return t1;
}
int main() {
TreeNode *t1;
TreeNode t11(1);
TreeNode t12(3);
TreeNode t13(2);
TreeNode t14(5);
TreeNode *t2;
TreeNode t21(2);
TreeNode t22(1);
TreeNode t23(3);
TreeNode t24(4);
TreeNode t25(7);
t1 = &t11;
t11.left = &t12;
t11.right = &t13;
t12.left = &t14;
t2 = &t21;
t21.left = &t22;
t21.right = &t23;
t22.right = &t24;
t23.right = &t25;
LevelOrder(Merge(t1, t2));
return 0;
}
输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b7d3779e4585e5e230d550408c41f530.png)