C++ 使用數組建立二叉樹 層序數組(方法二)
另外一種方法:見 C++ 使用數組建立二叉樹 層序數組(方法一)
試驗中,遍歷二叉樹的非遞歸方法 見我的另一篇博客:二叉樹的非遞歸遍歷——前序、中序、後序、層序、層序按行輸出
1、輸入數組要求
數組是按照層序輸入的,當該結點爲空時,用‘#’代替空的位置。
2、核心代碼
//層序數組構建二叉樹
BinaryTreeNode *ConstructBinaryTree(int *arr, int len, int i){
if (!arr || len < 1)return NULL;
BinaryTreeNode *root = NULL;
if (i < len && arr[i] != '#'){
root = new BinaryTreeNode();
if (root == NULL)return NULL;
root->data = arr[i];
root->lchild = ConstructBinaryTree(arr, len, 2 * i + 1);
root->rchild = ConstructBinaryTree(arr, len, 2 * i + 2);
}
return root;
}
3、實驗
實驗二叉樹:
1
/ \
2 3
/ \ \
4 5 6
/ \
7 8
實驗代碼:
void test2(){
BinaryTreeNode *t;
int data[] = { 1, 2, 3, 4, 5, '#', 6, '#', '#', 7, 8 };
t = ConstructBinaryTree(data, sizeof(data) / sizeof(data[0]), 0);
cout << "前序: ";
PreOrder(t);
cout << "中序: ";
inOrder(t);
cout << "後序: ";
postOrder(t);
cout << "層序: ";
LevelOrder(t);
cout << "層序--按行輸出:" << endl;
LevelOrderByRow(t);
}
int main()
{
test2();
return 0;
}