二叉树的遍历
来源:互联网 发布:webstorm mac怎么用 编辑:程序博客网 时间:2024/05/14 02:45
我的二叉树的遍历都是用递归实现的。二叉树的创建就不再说了,如果不懂可以看这几篇文章。
二叉树的实现(2)链表
http://blog.csdn.net/liuzuyi200/article/details/24232937
二叉树的几种实现方式(1)数组法
http://blog.csdn.net/liuzuyi200/article/details/24232453
所谓的遍历是以根节点做标准的,若根节点在左中右三个结点中最先输出,叫前序遍历,
以此类推,,若根节点在左中右三个结点中第二个输出,叫中序遍历,若根节点在左中右三个结点中最后输出,叫后序遍历,
(1)前序遍历的实现过程
void perorder( btree ptr)
{
if( ptr != NULL )
{
printf("[%2d]\n",ptr->data);
perorder( ptr->left );
perorder(ptr->right);
}
}
(2)中序遍历的实现过程
void inorder( btree ptr)
{
if( ptr != NULL )
{
inorder( ptr->left );
printf("[%2d]\n",ptr->data);
inorder(ptr->right);
}
}
(3)后序遍历的实现过程
void postorder( btree ptr)
{
if( ptr != NULL )
{
postorder( ptr->left );
postorder(ptr->right);
printf("[%2d]\n",ptr->data);
}
}
实现的过程
#include<stdio.h>#include<stdlib.h>struct tree{ int data; struct tree *left; struct tree *right;};typedef struct tree treenode;typedef treenode *btree;btree insert_node( btree root ,int value) { btree newnode; btree current; btree back; newnode = (btree ) malloc(sizeof(treenode)); newnode->data = value; newnode->left = NULL; newnode->left = NULL; if( root == NULL ) { return newnode; } else { current = root; while(current != NULL ) { back = current; if( current->data > value ) current = current->left; else current = current->right; } if(back->data > value) back->left =newnode; else back->right =newnode; } return root; }btree creatbtree( int *data,int len ){ btree root = NULL; int i; for( i = 0; i < len ; i++) { root = insert_node( root , data[i] ); } return root;}void postorder( btree ptr){ if( ptr != NULL ) { postorder( ptr->left ); postorder(ptr->right); printf("[%2d]\n",ptr->data); }}void perorder( btree ptr){ if( ptr != NULL ) { printf("[%2d]\n",ptr->data); perorder( ptr->left ); perorder(ptr->right); }}void inorder( btree ptr){ if( ptr != NULL ) { inorder( ptr->left ); printf("[%2d]\n",ptr->data); inorder(ptr->right); }}int main(){ btree root = NULL; int data[9] ={5,6,4,8,2,3,7,1,9}; root = creatbtree(data,9); printf("树的结点内容\n"); postorder(root); inorder(root); perorder(root); return 0 ; }
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- cocos2d-x 3.0rc1 编译cpp-tests工程
- JavaScript中日期和时间函数Date的简单用例
- Caused by: java.lang.NoClassDefFoundError和 Caused by: java.lang.ClassNotFoundException: Didn't find
- 【转载】视频跟踪的研究
- printf/scanf格式控制符的完整格式
- 二叉树的遍历
- [LeetCode] Populating Next Right Pointers in Each Node
- 插件配置的一些知识
- WIFI共享精灵显示启动不了或者一直在启动
- 用堆栈实现队列
- jquery操作select(取值,设置选中)
- 二分查找法
- GSM PDU 模式发送中文短信
- Oracle 使用 DBLINK详解