二叉树遍历
来源:互联网 发布:source tree mac 编辑:程序博客网 时间:2024/06/11 19:58
已知先序中序构树
#include <cstdio>#include <iostream>using namespace std;const int N = 50;int pre[N], in[N], post[N]; //存放先序,中序,后序的数组 int n;//树中元素个数struct node {int data;//数据node* lchild;//左子数指针node* rchild;//右子树指针};node* create(int prel, int prer, int inl, int inr) //根据先序和中序建立树 { //4个参数 先序的左右边界,中序的左右边界 if (prel>prer) //已经遍历完了,返回 {return NULL;//返回空指针}node* root = new node; //建立一个根结点,用来存放当前的树结点root->data = pre[prel]; // 因为是已知先序,所以当前树的值,一定等于先序的最左边的点 int k; //记录当前根节点在中序的下标for (k = inl; k <= inr; k++){if (in[k] == pre[prel]) //找到位置,跳出,k不再++break;}int numleft = k - inl; //当前树的左子树的数量root->lchild = create(prel + 1, prel + numleft, inl, k - 1); //将这部分存入左子树 root->rchild = create(prel + numleft + 1, prer, k + 1, inr); // 将这部分存入右子树return root; //返回根结点的地址,将整个树的结点连接起来}已知后序中序构树
#include <cstdio>#include <iostream>#include <queue>using namespace std;const int N = 50;int pre[N], in[N], post[N];//in中序,post后序int n;//结点个数struct Node {int data;//数据Node* lchild;//左子树指针Node* rchild;//右子树指针};Node* create(int postl, int postr, int inl, int inr)//4个参数 后序的左右边界,中序的左右边界 {if (postl>postr) //已经遍历完了,返回 {return NULL;}Node* root = new Node; //建立一个根结点,用来存放当前的树结点root->data = post[postr]; // 因为是已知后序,所以当前树的值,一定等于先序的最右边int k;for (k = inl; k<=inr; k++){if (in[k] == post[postr]) //找到位置,跳出,k不再++ break;}int numleft = k - inl;//当前树的左子树的数量 root->lchild = create(postl, postl + numleft - 1, inl, k - 1);//将这部分存入左子树 root->rchild = create(postl + numleft, postr - 1, k + 1, inr);// 将这部分存入右子树 return root; //返回根结点的地址,将整个树的结点连接起来 }
先序中序后序输出
void printfpost(node* root) {if (root == NULL)return;//遇到空指针返回printfpost(root->lchild);printfpost(root->rchild);printf("%d", root->data);//这三行放后面为后序,前面先序,中间中序输出num++;if (num<n) printf(" ");}
层次遍历输出
void bfs(Node* root) //层次遍历输出 {queue<Node*> q;int num = 0;q.push(root);//根结点入队while (!q.empty()){Node* now = q.front();q.pop();printf("%d", now->data);//输出此结点数据num++;if (num<n) printf(" ");if (now->lchild != NULL) q.push(now->lchild);//左右结点依次入队if (now->rchild != NULL) q.push(now->rchild);}putchar(10);//换行}
主函数
int main(){scanf("%d", &n);for (int i = 0; i<n; i++)//输入先序排列{scanf("%d", &pre[i]);//后序scanf("%d", &post[i]);}for (int i = 0; i<n; i++)//输入中序排列{scanf("%d", &in[i]);}node* root = create(0, n - 1, 0, n - 1);//构树,4个参数 先后序的左右边界,中序的左右边界 调用输出函数;}
阅读全文
1 0
- 二叉树遍历、分层遍历
- 遍历二叉树--二叉树
- 【树】遍历二叉树
- 二叉树遍历
- 二叉树遍历
- 二叉树的遍历
- (原创)遍历二叉树
- 二叉树遍历-php
- 查找--遍历二叉树
- 遍历二叉树
- 二叉树遍历规则
- 二叉树的遍历
- 二叉树遍历
- 遍历二叉树
- 二叉树遍历问题
- 二叉树遍历
- 二叉树遍历(zz)
- 二叉树的遍历
- RESTful @Controller和@RestController使用
- 使用0x3f3f3f3f表示无穷大
- C/C++ | 27-18 n的无序数组,求排序算法,并且要求时间复杂度为O(n)
- Rails 文件存储
- [libkcp] Part 1: 会话层
- 二叉树遍历
- uva512心得
- git 项目中用到的命令
- ThreadPoolExecutor使用介绍
- HDU6055 Regular polygon(计算几何,2017 HDU多校联赛 第2场)
- 图书管理系统
- mysql(四)
- 线程安全、线程私有变量
- 文件系统EXT3,EXT4和XFS的区别