二叉树的遍历
来源:互联网 发布:mac上哪里下游戏 编辑:程序博客网 时间:2024/05/28 09:31
二叉树的遍历分为三种,分别为前序遍历,中序遍历以及后序遍历。
由于二叉树可以看作递归类型,及由根节点及其左子树和右子树组成。每个子树也包括根节点和其左子树和右子树(左子树、右子树又可以看作另一个二叉树)。
前序遍历:根节点->左子树->右子树,对于每个子树也是这样的顺序。
中序遍历:左子树->根节点->右子树。
后序遍历:左子树->右子树->根节点。
可以用递归函数实现,访问每个子树时,相当于访问另一个子树。
#include<stdio.h>#include<stdlib.h>typedef struct Node{ char data; struct Node* LChild; struct Node* RChild;}BiTNode,*BiTree;/*void createTree(BiTree* root){ BiTNode* s[15]; char a[15]={'A','B','C','s','D','s','E','s','s','F','G','s','s','s','H'}; *root=s[0]; int i; for(i=0;i<15;i++){ s[i]=(BiTNode*)malloc(sizeof(BiTNode)); s[i]->LChild = NULL; s[i]->RChild = NULL; s[i]->data = a[i]; } for(i=0;i<7;i++){ if(s[2*i+1]->data != 's'){ s[i]->LChild = s[2*i+1]; } if(s[2*i+2]->data != 's'){ s[i]->RChild = s[2*i+2]; } }}*/void CreateBiTree(BiTree *bt){ char ch; ch = getchar(); if(ch == '.') *bt=NULL; else{ *bt = (BiTree)malloc(sizeof(BiTNode)); (*bt)->data = ch; CreateBiTree(&((*bt)->LChild)); CreateBiTree(&((*bt)->RChild)); }}void PreOrder(BiTree root){ if(root != NULL){ printf("%c\n",root->data); PreOrder(root->LChild); PreOrder(root->RChild); }}void InOrder(BiTree root){ if(root != NULL){ InOrder(root->LChild); printf("%c\n",root->data); InOrder(root->RChild); }}void PostOrder(BiTree root){ if(root != NULL){ PostOrder(root->LChild); PostOrder(root->RChild); printf("%c\n",root->data); }}int main(){ BiTree root; CreateBiTree(&root); InOrder(root); return 0;}
阅读全文
1 0
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 那些年我们遇到的坑(3)-basePackages和scanBasePackages
- Spring boot 单元测试
- Ie9以下的input输入框placeholder属性兼容方案
- 设计模式之工厂方法模式
- 第1.7章 scrapy之ip代理的使用
- 二叉树的遍历
- 合并两个序列
- day03
- 【Mybatis】基础了解
- nginx修改nginx.conf文件后reload出现的错误
- Java 程序员必须掌握的 Linux 命令
- Codeforces Ultra-Fast Mathematician
- 《Mastering R for Quantitative Finance》Chapter1笔记
- InputArray和OutputArray的那些事