二叉树的创建和前中后三种遍历方法
来源:互联网 发布:淘宝卖家快捷回复短语 编辑:程序博客网 时间:2024/05/19 17:51
头文件:
#include<stdlib.h>#include<stdio.h>typedef struct bnode{ int data;//结点数据类型 struct bnode *lchild, *rchild;// 定义左右孩子为指针类型}btree;btree *insert_node(btree *root, int node) //插入结点的函数{ btree *newpointer; btree *currentpointer; btree *parentpointer; newpointer = (btree *)malloc(sizeof(btree));//向系统申请内存的函数malloc newpointer->data=node; newpointer->lchild=NULL; newpointer->rchild=NULL; if(root==NULL) return newpointer; else { currentpointer=root; while(currentpointer!=NULL) { parentpointer=currentpointer; //若当前插入的值比父结点小,放在左,否则放在右 if(currentpointer->data>node) currentpointer=currentpointer->lchild; else currentpointer=currentpointer->rchild; } if(parentpointer->data>node) parentpointer->lchild=newpointer; else parentpointer->rchild=newpointer; } return root;}btree *create_btree(int data[], int len) //建立二叉树{ int i; btree *root = NULL; for(i=0; i<len; i++) { root=insert_node(root,data[i]);//调用插入二叉树结点的函数 } return root;}
二叉树的前序非递归遍历:
//前序遍历,从根节点开始,再到左子树 再到右子树void preorder(btree *root){ btree *p, *s[100]; int top=0; p=root; while((p!=NULL)||(top>0)) { while(p!=NULL) { printf("%d",p->data);//直接输出根节点,然后左然后右 s[++top]=p; p=p->lchild; } p=s[top--]; p=p->rchild; }}int main(){ btree *root=NULL; int value, index, nodelist[20]; index=0; scanf("%d", &value); while(value!=0) { nodelist[index]=value; index++; scanf("%d",&value); } root= create_btree(nodelist,index); preorder(root); return 0;}
<pre name="code" class="csharp">void inorder(btree *root){ if(root!=NULL) { inorder(root->lchild);// left child printf("%d",root->data); // root inorder(root->rchild);// right child }}int main(){ btree *root=NULL; int value, index, nodelist[100]; index=0; scanf("%d",&value); while(value!=0) { nodelist[index]=value; index++; scanf("%d",&value); } root=create_btree(nodelist,index); inorder(root); return 0;}
二叉树的后序递归遍历: 先左子树,再右子树,再根节点
void postorder(btree *root){ if(root!=NULL) { postorder(root->lchild);// left postorder(root->rchild);// right printf("%d",root->data); // root }}int main(){ btree *root = NULL; int value,index,nodelist[100]; index=0; scanf("%d",&value); while(value!=0) { nodelist[index]=value; index++; scanf("%d",&value); } root=create_btree(nodelist,index); postorder(root);}
0 0
- 二叉树的创建和前中后三种遍历方法
- 二叉树的创建和各种遍历方法
- 二叉树的创建和遍历方法(上)
- 二叉树的创建和遍历方法(下)
- 二叉树的创建以及遍历方法
- 二叉搜索树的创建和遍历
- 二叉树的创建,遍历和释放
- 简单的二叉树创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和遍历
- 数据结构---二叉树的创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和遍历
- 二叉树的创建和前序中序后序遍历
- 二叉树的创建和遍历
- 【Linux】僵尸进程的检测,清理和避免
- 从android应用程序跳转到系统的各个设置页面
- 后缀数组——罗穗骞倍增算法代码详解
- javabean和json的常用转换解析
- 4.Benchmark SQL 数据库测试工具代码——关于导入类
- 二叉树的创建和前中后三种遍历方法
- Android中使用 listView 绘制表格
- 友善之臂4412开发板android应用层通过jni直接控制除LED、蜂鸣器外的其它IO口,系统直接重启问题
- Sqlite常用表查询语句
- 5.Benchmark SQL 数据库测试工具代码——关于辅助类
- 常见网页状态码之我想记住
- C++11: random #1
- 使用X-Frame-Options防止网页被Frame
- 6.Benchmark SQL 数据库测试工具代码——执行SQL类