102反転バイナリツリー(25分)

1タイトル

バイナリツリー(25分)を反転102
以下が最大ハウエル@twitterからのものです。

グーグル:当社のエンジニアの90%は、あなたが書いたソフトウェア(自作)を使用していますが、ホワイトボード上のバイナリツリー反転ので、オフに性交することはできません。

今、それはあなたがバイナリツリーを反転させることができることを証明するためにあなたの番です!

入力仕様:
各入力ファイルは、1つのテストケースが含まれています。各場合について、最初の行は、ツリー内のノードの総数であるN(≤10)整数陽性を与える- 、したがってノードは、0からN-1まで番号付けされています。次いで、N行が0からN-1までのノードに、それぞれ対応するに従い、ノードの左及び右の子のインデックスを与えます。子が存在しない場合は、 -の位置に置かれます。子供の任意のペアは、スペースで区切られます。

出力仕様:
各テストケースについて、最初の行のレベル順序を印刷し、次に2行目の逆ツリーのインオーダートラバース配列。正確に一つの隣接する任意の数字の間のスペース、および行の末尾に余分なスペースがなければなりません。

Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

      
    
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

2解析されました

  • 問題の意味:反転バイナリツリー、出力シーケンス順序を求めた後、ノードの左と右の子ノードのそれぞれに与えられた2進数と
  • アイデア:
    • バイナリツリーの静的バイナリツリーを作成します。1.
    • 図2に示すように、逆の順序トラバーサルを有するバイナリツリーを(再帰的トラバース後にスイッチングノード約​​)
    • 図3に示すように、反転後の2進シーケンス出力のシーケンス番号

3参照コード

#include <cstdio>
#include <queue>
#include <algorithm>

using std::queue;
using std::swap;

const int MAXN = 20;
bool notRoot[MAXN] = {false};
int num = 0;
int N;

struct node
{
    int lchild;
    int rchild;
}Node[MAXN];

int strToNum(char  c){
    if(c == '-'){
        return -1;
    }else{
        notRoot[c - '0'] = true;
        return c - '0';
    }
}

int findRoot(){
    for (int i = 0; i < N; ++i)
    {
        if(notRoot[i] == false){
            return i;
        }
    }
}

void Reverse(int root){
    if(root == -1){
        return;
    }

    Reverse(Node[root].lchild);
    Reverse(Node[root].rchild);
    swap(Node[root].lchild, Node[root].rchild);
}

void print(int root){
    printf("%d", root);
    num++;

    if(num < N){
        printf(" ");
    }else{
        printf("\n");
    }

}


void layerorder(int root){
    queue<int> q;
    q.push(root);

    while(!q.empty()){
        int now = q.front();
        q.pop();

        print(now);

        if(Node[now].lchild != -1){
            q.push(Node[now].lchild);
        }
        if(Node[now].rchild != -1){
            q.push(Node[now].rchild);
        }
    }
}

void inorder(int root){
    if(root == -1){
        return;
    }

    inorder(Node[root].lchild);
    print(root);
    inorder(Node[root].rchild);
}

int main(){
    scanf("%d", &N);

    char lchild, rchild;
    for (int i = 0; i < N; ++i)
    {
        scanf("%*c%c %c", &lchild, &rchild);
        Node[i].lchild = strToNum(lchild);
        Node[i].rchild = strToNum(rchild);
    }

    int root = findRoot();

    Reverse(root);

    layerorder(root);
    num = 0;
    inorder(root);

    return 0;
}


公開された321元の記事 ウォン称賛51 ビュー40000 +

おすすめ

転載: blog.csdn.net/qq_33375598/article/details/104129592