# 數據結構入門——完全二叉樹

7
1 2 3 4 5 6 7

—1
-2—3
4-5-6-7

``````//輸入完全二叉樹的個數
//依次輸入完全二叉樹的值
//打印二叉樹到temp.txt中
#include<iostream>
#include<math.h>
#include <fstream>
using namespace std;
#define TYPE int
//定義元素類型
struct CBTNode
{
TYPE element;
CBTNode *lchild;
CBTNode *rchild;
};

class CBinTree
{
public:
CBTNode *root;
CBinTree(int num);
~CBinTree();
int CBinTreeHeight(int num);
void print(int num);

};

CBinTree::CBinTree(int num)
{
root = new CBTNode[num + 1];//定義從root[1]開始放置元素
TYPE ch;
for (int i = 1; i < num / 2 + 1; ++i)
{
root[i].lchild = &root[2 * i];
root[i].rchild = &root[2 * i + 1];
}
for (int i = 1; i < num + 1; i++)
{
cin >> ch;
root[i].element = ch;
}
}
CBinTree::~CBinTree()
{
if (root != NULL)
delete[] root;
}

int CBinTree::CBinTreeHeight(int num)
{
int i = 0;
while (num != 0)
{
i++;
num = num / 2;
}
return i;
}
void CBinTree::print(int num)
{
ofstream mycout("temp.txt");
int m = CBinTreeHeight(num), n = int(pow(2, m));
int q = n / 2 - 1;
int k = 0, j = 0;
for (int i = 0; i < m - 1; i++, q = q / 2)//m表示行數，先輸出m-1行滿二叉樹
{
j = j + int(pow(2, i));//j表示當前行的總輸出元素個數；
for (int l = 0; l <q; l++)
{
mycout << '\t';//用tab符號放置元素，防止輸入int時因為位數影響輸入效果
}
k++;
mycout << root[k].element;
while (k < j)
{
for (int l = 0; l <2 * q + 2; l++)
{
mycout << '\t';
}
k++;
mycout << root[k].element;
}
mycout << endl;
}

for (k++; k < num + 1; k++)
{
mycout << root[k].element << '\t' << '\t';
}
mycout << endl;
}

int main()
{
int num;
cin >> num;
CBinTree tree(num);
tree.print(num);

system("pause");
return 0;
}``````