1. 程式人生 > 其它 >C++建立順序儲存完全二叉樹並以廣義表形式輸出

C++建立順序儲存完全二叉樹並以廣義表形式輸出

技術標籤:C/C++二叉樹

建立順序儲存完全二叉樹並以廣義表形式輸出

題目要求:

假設用順序表來表示一棵完全二叉樹。從根到葉結點按層次從 1 開始編號,同一層次從左到右編號,資料儲存在對應的陣列元素中。試編寫演算法由此順序儲存結構建立該二叉樹的二叉連結串列。

輸入格式:

輸入只有一行,為順序輸入的從根節點開始的各個節點元素,它們之間用空格隔開,整個輸入以 $ 結束。

輸出格式:

輸出有一行,為二叉樹結構的廣義表示式。

樣例輸入:

A B C D $

樣例輸出:

A(B(D),C)

解題思路:

由完全二叉樹的特點可得,若父親結點的索引為 i,那麼該父親結點的左孩子的索引為 2 * i + 1,右孩子的索引為 2 * i + 2。

程式碼編寫:

#include <iostream>
#include <string>

using namespace std;

class Node {
public:
    char data;
    Node *lchild;
    Node *rchild;
    
    Node(char _data) {
        data = _data;
        lchild = NULL;
        rchild = NULL;
    }
    
    ~Node() {
        if(lchild != NULL
) delete lchild; if(rchild != NULL) delete rchild; } Node *build(string &str, int index = 0) { int len = str.size(); if(len <= index) return NULL; Node *p = new Node(str[index]); p->lchild = build(str, 2 * index + 1); p->rchild =
build(str, 2 * index + 2); return p; } void show() { cout << data; if(lchild != NULL) { cout << '('; lchild->show(); if(rchild == NULL) { cout << ')'; } } if(rchild != NULL) { if(lchild == NULL) { cout << '('; } cout << ','; rchild->show(); cout << ')'; } } }; class BinaryTree { private: Node *root; public: BinaryTree() { root = NULL; } ~BinaryTree() { if(root != NULL) delete root; } void build(string &str) { root = root->build(str); } void show() { if(root == NULL) return ; root->show(); } }; int main() { char ch; string str; while(true) { cin >> ch; if(ch != '$') str.push_back(ch); else break; } BinaryTree binaryTree; binaryTree.build(str); binaryTree.show(); return 0; }