—【輸入:】
—第一行:多叉樹中的結點個數n(<=300,樹中結點的編號為1到n)
—以下n行:i和j,i的父親j。父親結點為0的結點是樹根。
—【輸出:】
—一行,輸出多叉樹對應二叉樹的中序遍歷結果,每兩個結點之間一個空格。
—【樣例輸入:】
—7
—2 1
—3 1
—4 1
—5 2
—6 2
—7 4
—1 0
—【樣例輸出:】
—7 4 3 6 5 2 1
首先這道題得知道多叉樹與二叉樹之間的轉換規則——左孩子右兄弟。意思就是說,一棵由多叉樹轉換而來的二叉樹的任意結點的左孩子是它在原樹中的孩子,它的右孩子結點是它在原樹中的兄弟結點。
如圖所示,第二棵樹中標號為4的結點的左兒子是它在第一棵樹中的孩子結點,而它的右孩子3結點是它在原樹中的兄弟結點。
所以這道題就十分好做了
首先輸入數據n,表示有n個結點。
接下來一個for循環,輸入結點號以及它的父親結點;
用一個結構體存儲樹。
邊輸入邊轉換。
最后一個遞歸中序遍歷二叉樹輸出結果。
源碼如下:
#include<iostream>
const int maxn=10000;
struct tree
{
int lson;
int rson;
tree() {lson = 0; rson = 0;}
};
tree a[maxn];
int tou;
int bianli(int x)
{
if(a[x].lson!=0)
{
bianli(a[x].lson);
}
std::cout<<x<<' ';
if(a[x].rson!=0) bianli(a[x].rson);
}
int main()
{
int n,i,j;
std::cin>>n;
for(int z=1;z<=n;z++)
{
std::cin>>i>>j;
if(j==0) tou=i;
else
{
if(a[j].lson==0)
{
a[j].lson=i;
}
else
{
a[i].rson=a[j].lson;
a[j].lson=i;
}
}
}
bianli(tou);
}

