c语言二叉链表的非递归建立,用非递归方法创建一个二叉树,再用递归方法先中后序遍历,然后用非递归层次遍历...

include

#define Null 0

struct tree_node \\声明二差树节点结构

{

int data;

struct tree_node *left;

struct tree_node *right;

};

typedef struct tree_node tree_list;

typedef tree_list *btree;

struct s_node \\声明堆栈结构

{

btree data;

struct s_node *next;

};

typedef struct s_node s_list;

typedef s_list *link;

btree insert_btree(btree root,int node) \\插入二叉树节点

{

btree new,parent,current;

new=(btree)malloc(sizeof(tree_list));

new->data=node;

new->left=Null;

new->right=Null;

if(root==Null)

{

return new;

}

else

{

current=root;

while(current!=Null)

{

parent=current;

if(new->datadata)

{

current=current->left;

}

else

{

current=current->right;

}

}

if(new->datadata)

{

parent->left=new;

}

else

{

parent->right=new;

}

return root;

}

}

btree create_btree(int *nodlist,int len) \\建立二叉树

{

btree root=Null;

int i;

for(i=0;i

{

root=insert_btree(root,nodlist[i]);

}

return root;

}

link push(link stack,btree value) \\入栈函数

{

link new;

new=(link)malloc(sizeof(s_list));

new->data=value;

new->next=Null;

if(stack==Null)

{

stack=new;

return stack;

}

else

{

new->next=stack;

stack=new;

return stack;

}

}

link pop(link stack,btree *value) \\出栈函数

{

link pointer;

pointer=stack;

if(pointer==Null)

{

return Null;

}

else

{

stack=stack->next;

*value=pointer->data;

free(pointer);

return stack;

}

}

void search_btree(btree root) \\非递归层次遍历

{

link stack=Null;

btree value1;

int i=0;

value1=root;

printf("%d\n",value1->data);

while(stack!=Null||value1->left!=Null||value1->right!=Null)

{

if(value1==Null)

{

stack=pop(stack,&value1);

printf("%d\n",value1->data);

}

else if(value1->left!=Null&&value1->right!=Null)

{

printf("%d\n",value1->right->data);

stack=push(stack,value1->left);

value1=value1->right;

}

else if(value1->left==Null&&value1->right==Null)

{

stack=pop(stack,&value1);

if(value1!=Null)

{

printf("%d\n",value1->data);

}

}

else if(value1->left!=Null&&value1->right==Null)

{

stack=push(stack,value1->left);

value1=Null;

}

else if(value1->left==Null&&value1->right!=Null)

{

printf("%d\n",value1->right->data);

value1=value1->right;

}

}

}

void inorder_btree(btree root) \\递归法中序遍历

{

if(root!=Null)

{

inorder_btree(root->left);

printf("%d\n",root->data);

inorder_btree(root->right);

}

}

main()

{

int i,index,data;

int nodlist[16]={6,9,7,4,5,2,1,8,12};

btree root,root1;

link stack;

index=9;

root=create_btree(nodlist,index);

search_btree(root);

getch();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值