1102 Invert a Binary Tree(25 分)--二叉树反转左右孩子

总结:

1.做这道题的时候开始没读懂题意,把invert意思记错了,导致左右子树是反的,很无语,刚过了六级看来不够,继续学习英语很有必要。

2.做这道题的时候思路应该是很明确的,但是花了一个多小时,为啥呢》》》分析如下:

思路:在读入数据的时候确定根节点,然后保存每一个节点的左右孩子节点(反着保存),然后用一维数组递归建立二叉树,层次遍历就很好解决了,中序遍历也很ok,然后这道题应该是很easy了。但是:我想着怎么能简单点----不用递归,用更简单的方法解决建立二叉树以及遍历问题,事实上我对递归理解不够深刻以致于折腾好久还是没解决,最后屈服了。

代码:

#include<iostream>
#include<stack>
using namespace std;
int node[1000];
int p[40][2];
int root[50];
stack<int> pp;
int flag1 = 0; int n = -1;
void creat(int root2,int ti)
{
    node[ti] = root2;
    if (p[node[ti]][0] != -1)creat(p[node[ti]][0],2*ti+1);
    if (p[node[ti]][1] != -1)creat(p[node[ti]][1], 2 * ti + 2);
}
void inorder(int it)
{
    if (node[it]<0)return;
    inorder(2*it+1);
    if (node[it] >= 0){ cout << node[it]; flag1++; if (flag1 != n)cout << " "; }
    inorder(2*it+2);
}
int main()
{
    int root1;
    fill(node,node+1000,-1);
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        char a, b;
        cin >> a >> b;
        if (a != '-'){ int a1 = a - 48; p[i][1] = a1; root[a1] = -1; }
        else p[i][1] = -1;
        if (b != '-'){ p[i][0] = b - 48; root[b - 48] = -1; }
        else p[i][0] = -1;
    }
    for (int i = 0; i < n; i++)
    {
        if (root[i] != -1)root1 = i;
    }
    //cout <<"root为:"<< root1 << endl;
    creat(root1,0);
    for (int i = 0,flag=0; i <100; i++)
    {
        if (node[i] >= 0){ cout << node[i]; flag++; if (flag != n)cout << " "; }
        
    }
    cout << endl;
    inorder(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/luoshiyong123/article/details/81982408
今日推荐