#include<iostream>
using namespace std;
const int N= 100010; //定义
const int nil = -1; //定义一个标记
struct Node{
int parent,left,right;
}; //定义一个结构体树,双亲结点,左孩子,右孩子
Node L[N]; //结构体数组
int D[N],H[N],n; //深度数组,高度数组
/* parnet=父节点
sibling = 兄弟结点
degree = 子节点个数
depth = 结点深度
height = 结点高
root =树根 internal = 内部结点 leaf = 叶子节点
输入:
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
*/
void Preorder(int u)
{
if(u==nil)
return;
cout << u;
Preorder(L[u].left);
Preorder(L[u].right);
}
void Inorder(int u)
{
if(u==nil)
return;
Inorder(L[u].left);
cout << u;
Inorder(L[u].right);
}
void Postorder(int u)
{
if(u==nil)
return;
Postorder(L[u].left);
Postorder(L[u].right);
cout << u;
}
void Depth(int u,int d) //深度递归求结点的深度
{
if(u == nil) return;
D[u] = d;
Depth(L[u].left,d+1);
Depth(L[u].right,d+1);
}
int Height(int u) //递归求结点的高度
{
int h1=0,h2=0;
if(L[u].left != nil) h1 = Height(L[u].left)+1;
if(L[u].right != nil) h2 = Height(L[u].right)+1;
return H[u] = (h1>h2?h1:h2);
}
int sibling(int u) //求兄弟结点 L[L[u].parent].left为此结点的双亲结点下的另一个孩子结点
{
if(L[u].parent == nil) return nil;
if(L[L[u].parent].left != u && L[L[u].parent].left != nil) return L[L[u].parent].left;
if(L[L[u].parent].right != u && L[L[u].parent].right !=nil) return L[L[u].parent].right;
return nil;
}
void print(int u) //打印这个二叉树的情况
{
cout << "Node " << u << ":";
cout << "parent =" << L[u].parent << ",";
cout << "sibling =" << sibling(u) <<",";
cout << "degree =";
int cnt =0;
if(L[u].left!=nil) cnt++;
if(L[u].right!=nil) cnt++;
cout <<cnt <<",";
cout <<"depth =" << D[u] <<",";
cout << "height =" << H[u] <<",";
if(L[u].parent ==nil) cout << "root" <<endl;
else if(L[u].left == nil && L[u].right == nil) cout << "leaf" <<endl;
else cout << "internal node" <<endl;
}
int main()
{
int i,l,r,root;
cin >>n;
for(i=0;i<n;i++) L[i].left = L[i].parent = L[i].right = nil; //对所有结点都进行初始化,设为-1
for(i=0;i<n;i++)
{
int x;
cin >>x >> l>> r;
L[x].left =l;
L[x].right=r;
if(L[x].left!=nil) L[l].parent =x;
if(L[x].right!=nil) L[r].parent =x;
}
for(i=0;i<n;i++)
if(L[i].parent == nil) root=i; //求这个二叉树的根节点
Depth(root,0);
Height(0);
for(i=0;i<n;i++) print(i);
cout <<endl;
cout << "Preorder" <<endl;
Preorder(root) ;
cout <<endl;
cout << "Inorder" <<endl;
Inorder(root);
cout <<endl;
cout <<"Post" <<endl;
Postorder(root);
cout <<endl;
return 0;
}
09-08
1296
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)