1102 Invert a Binary Tree (25分)(二叉树的遍历)

二叉树的遍历是以DFS和BFS为基础的,无非是在DFS和BFS上面的变形,熟练掌握了BFS和DFS以后,这种类型的题目也就没有什么太大的难度了

题目描述如下:
在这里插入图片描述
在这里插入图片描述
题目大致意思:
一棵树的左右子树交换后,输出其层序遍历序列和中序遍历序列。
大致思路:
在录入树的节点信息时,就可以将树的左右子树进行颠倒录入,在录入的过程中完成反转。在建立二叉树时可以使用静态的方法建立,对于本道题目来说使用静态的方法更为简单。建树完成后,对该树进行广度优先遍历和递归的深度优先遍历即可。
提交结果如下:
在这里插入图片描述
提交的代码如下:

#include<iostream>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
bool is_root[10];
struct Node
{
    int lchild;
    int rchild;
};
Node node[10];
int n;
int sum=0;
void level_order(int root);
void in_order(int root);
int main()
{
    fill(is_root, is_root + 10, true);
    cin >> n;
    for (int i = 0;i < n;i++)
    {
        string str1, str2;
        cin >> str1 >> str2;
        if (str1 >= "0" && str1 <= "9")
        {
            node[i].rchild = atoi(str1.c_str());
            is_root[atoi(str1.c_str())] = false;
        }
        else
            node[i].rchild = -1;
        if (str2 >= "0" && str2 <= "9")
        {
            node[i].lchild = atoi(str2.c_str());
            is_root[atoi(str2.c_str())] = false;
        }
        else
            node[i].lchild = -1;
    }
    int root;
    for (root = 0;root < n;root++)
    {
        if (is_root[root] == true)
            break;
    }
    level_order(root);
    in_order(root);
}
void level_order(int root)
{
    int index = 0;
    queue<int> que;
    que.push(root);
    while (!que.empty())
    {
        int top = que.front();
        que.pop();
        if (index < n - 1)
        {
            cout << top << " ";
        }
        else
        {
            cout << top << endl;
        }
        index++;
        if (node[top].lchild != -1)
            que.push(node[top].lchild);
        if (node[top].rchild != -1)
            que.push(node[top].rchild);
    }
}
void in_order(int root)
{
    if(root==-1)
        return;
    in_order(node[root].lchild);
    if(sum<n-1)
        cout<<root<<" ";
    else
        cout<<root<<endl;
    sum++;
    in_order(node[root].rchild);
}

本次提交后累计得分为1594。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值