說明:本文所用方法僅針對多叉樹,並不適用於二叉樹。
實現思路:首先,設計樹結點結構,其中應該包含結點數據和孩子結點的位置,本文用結構體實現,data表示結點數據,children是一個不定長數組,用於保存孩子結點的位置。然后,定義一個數組testTree[],用於存儲樹結點。之后,靜態的實現下圖所示的測試樹。最后,用遞歸方法遍歷該測試樹。
測試所用的樹結構如下圖所示:
測試遍歷路徑如下圖:
C++實現:
#include<iostream>
#include<vector>
using namespace std;
struct Node //樹結點的結構
{
int data;
vector<int> children;
};
void traverseTree(struct Node tree[], int index)
{
int count = tree[index].children.size(); //計算n結點孩子的個數
cout<<tree[index].data<<" ";
while(count > 0)
{
count--;
traverseTree(tree,tree[index].children.at(count));
}
}
int main()
{
struct Node testTree[6]; //第一六個樹結點
for (int i=0; i<6; i++) //初始化六個結點的內容,分別為1,2,3,4,5,6
testTree[i].data = i+1;
//初始化樹,為結點連上紙條
testTree[0].children.push_back(1);
testTree[0].children.push_back(2);
testTree[0].children.push_back(3);
testTree[2].children.push_back(4);
testTree[2].children.push_back(5);
//testTree[0]是樹根,訪問樹
traverseTree(testTree,0);
cout<<endl;
return 0;
}
運行結果: