/*
* 二叉树
*
* (将完全二叉树的数组形式改为链表形式)
*
* 1
* 2 3
* 4 5 6 7
* 8
*
*/
#include <iostream>
#define MAX 10
using namespace std;
typedef struct btnode{
int data;
struct btnode * lchild;
struct btnode * rchild;
}btnode;
int main() {
int a[]={0,1,2,3,4,5,6,7,8};
int n=8;
btnode * root;
btnode * create_bin(int arr[],int n,int i);
//数组先序建立二叉树,并返回根结点指针。下标从1开始
//n是元素个数,i是计数器
void trav_bi_preorder(btnode * root); //先序遍历二叉树
void trav_bi_inorder(btnode * root); //中序遍历二叉树(递归算法)
void trav_bi_inorder_nonrecur(btnode *root);
//中序遍历二叉树(非递归算法)
root=create_bin(a,n,1);
// trav_bi_preorder(root); //12485367
trav_bi_inorder(root);
cout << endl;
trav_bi_inorder_nonrecur(root);
return 0;
}
//利用数组元素建立完全二叉树
btnode * create_bin(int arr[],int n,int i){
btnode * root=(btnode *)malloc(sizeof(btnode));
if(i<=n){
root->data=arr[i];
root->lchild=create_bin(arr,n,2*i);
root->rchild=create_bin(arr,n,2*i+1);
return root;
}else{
return NULL;
}
}
//先序遍历二叉树(递归算法)
void trav_bi_preorder(btnode * root){
if(root!=NULL){
cout << root->data;
trav_bi_preorder(root->lchild);
trav_bi_preorder(root->rchild);
}
}
//中序遍历二叉树(递归算法)
void trav_bi_inorder(btnode * root){
if(root!=NULL){
trav_bi_inorder(root->lchild);
cout << root->data;
trav_bi_inorder(root->rchild);
}
}
/*
* 中序遍历二叉树(非递归算法)
*
* 中序遍历就是:从根开始一直沿着左支的方向去走,走到头之后,最左边
* 的结点作为第一个结点。然后沿途依次返回,遇到“分叉”的时候,向右边
* 转一个结点的位置,然后再一直沿着左支的方向走,走到头之后。。。
* 。。。一直到最后一个结点完事
*
* (这样用栈解决,每一个元素都是一个“中转站”,不断的回退,有中转就
* 压入栈中。。。)
*/
void trav_bi_inorder_nonrecur(btnode *root){
btnode * st[MAX],* p,*q;
int top=-1;
st[++top]=root;
p=root;
while(top!=-1){
//所有元素都从栈里出,整个大前提就是栈不空
//从当前结点一路向左
while(p!=NULL){
st[++top]=p->lchild;
p=p->lchild;
}
top--;
// 上面的while一路向左,最后NULL一定入栈。
//所以要用这句话干掉NULL
// 下面的if,可能弹出元素的右子是NULL,故
//NULL入栈,这时while不会执行,这句就干掉NULL;
//若右子不为NULL,就会执行while,所以仍然需要这
//句话干掉NULL
if(top!=-1){
p=st[top--];
cout << p->data;
st[++top]=p->rchild;
p=p->rchild;
}
}
}