PAT(Advanced)1102 Invert a Binary Tree C++實現

PAT(Advanced)甲級1102 Invert a Binary Tree C++實現

題目鏈接

1102 Invert a Binary Tree

題目大意

給定二叉樹將其左右子樹逆轉,輸出逆轉後層次遍歷和中序遍歷的序列

算法思路

根據題意及二叉樹先序遍歷定義,找出根節點,並從根節點開始,將二叉樹根節點的左右子樹交換,再遞歸地轉換根節點的左右子樹,根節點子樹的左右子樹也必須交換,遞歸地,所有結點的左右子樹都交換一次即可,在輸出層次遍歷序列和中序遍歷序列

void invert(int p) {
    if (p == -1) {
        return;
    }
    swap(binaryTree[p].left, binaryTree[p].right);
    invert(binaryTree[p].left);
    invert(binaryTree[p].right);
}

AC代碼

/*
author : eclipse
email  : [email protected]
time   : Fri Jun 26 23:23:37 2020
*/
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int left;
    int right;
};

bool flag = true;

vector<Node> binaryTree;
int root;

void levelOrderTraverse() {
    queue<int> q;
    q.push(root);
    while (!q.empty()) {
        int front = q.front();
        q.pop();
        if (binaryTree[front].left != -1) {
            q.push(binaryTree[front].left);
        }
        if (binaryTree[front].right != -1) {
            q.push(binaryTree[front].right);
        }
        if (front == root) {
            printf("%d", front);
        } else {
            printf(" %d", front);
        }
    }
}

void inOrderTraverse(int p) {
    if (p == -1) {
        return;
    }
    inOrderTraverse(binaryTree[p].left);
    if (flag) {
        printf("%d", p);
        flag = false;
    } else {
        printf(" %d", p);
    }
    inOrderTraverse(binaryTree[p].right);
}

void invert(int p) {
    if (p == -1) {
        return;
    }
    swap(binaryTree[p].left, binaryTree[p].right);
    invert(binaryTree[p].left);
    invert(binaryTree[p].right);
}

int main(int argc, char const *argv[]) {
    int N;
    scanf("%d", &N);
    binaryTree.resize(N);
    vector<bool> children;
    children.resize(N);
    for (int i = 0; i < N; i++) {
        string left, right;
        cin >> left >> right;
        if (left == "-") {
            binaryTree[i].left = -1;
        } else {
            int child = atoi(left.c_str());
            children[child] = true;
            binaryTree[i].left = child;
        }
        if (right == "-") {
            binaryTree[i].right = -1;
        } else {
            int child = atoi(right.c_str());
            children[child] = true;
            binaryTree[i].right = child;
        }
    }
    for (int i = 0; i < children.size(); i++) {
        if (!children[i]) {
            root = i;
            break;
        }
    }
    invert(root);
    levelOrderTraverse();
    printf("\n");
    inOrderTraverse(root);
    return 0;
}

樣例輸入

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

樣例輸出

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

鳴謝

PAT

最後

  • 由於博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章