今年我是大三,准备了下面试字节跳动的后台C++开发,当接到笔试的时候就很兴奋,打开一看编程题2道
第一道题目袋盖如下:(我只记得题目的大致意思)
一个满二叉树有n层,请你输出这个二叉树的镜像,测试用例如下:
输入

输出:

代码如何下:大概意思就是将一个二叉树的左右孩子进行交换即可。
#include<iostream>
//二叉树镜像
using namespace std;
typedef struct Node{
char data;
struct Node *Lchild;
struct Node *Rchild;
}*Tree;
void out(Tree &T){
if(T){
cout<<T->data<<" ";
out(T->Lchild);
out(T->Rchild);
}
}
二叉树的左右孩子进行交换即可
void out2(Tree &T){
if(T){
Tree temp=T->Lchild;//交换是用到的中间变量
//交换左右节点
T->Lchild=T->Rchild;
T->Rchild=temp;
//再次递归即可
out2(T->Lchild);
out2(T->Rchild);
}
}
void input(Tree &T){
char ch;
cin>>ch;
if(ch=='#'){
T=NULL;
}
else{
T=new Node;
T->data=ch;
input(T->Lchild);
input(T->Rchild);
}
}
int main(){
while(true){
Tree T;
input(T);
out(T);
cout<<"交换后"<<endl;
out2(T);
out(T);
}
return 0;
}
大三学生准备面试字节跳动后台C++开发,笔试有两道编程题,其中一道是输出n层满二叉树的镜像,解题思路是将二叉树的左右孩子进行交换。

7729

被折叠的 条评论
为什么被折叠?



