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;
}