六、树和二叉树--(3)已知先序遍历和中序遍历求后序遍历
来源:互联网 发布:高中化学大全软件下载 编辑:程序博客网 时间:2024/05/22 05:20
摘自计蒜客:http://www.jisuanke.com/course/35/1397
算法过程如下:在先序遍历中知道根结点的编号,在中序遍历中找到根结点所在位置,那么位置前面的结点就是根结点的左
子树上的结点,位置后面的结点就是右子树上的结点。按照以上方法递归建立起一个二叉树,最后调用二叉树的后序遍历函
数,输出后序遍历。
#include<iostream>
#include<string>using namespace std;
class Node {
public:
int data;
Node *lchild, *rchild;
Node(int _data) {
data = _data;
lchild = NULL;
rchild = NULL;
}
~Node() {
if (lchild != NULL) {
delete lchild;
}
if (rchild != NULL) {
delete rchild;
}
}
void postorder() {
if (lchild != NULL) {
lchild->postorder();
}
if (rchild != NULL) {
rchild->postorder();
}
cout << data << " ";
}
Node *build(const string &pre_str, const string &in_str, int len) {
Node *p = new Node(pre_str[0]-'0');
int pos = in_str.find(pre_str[0]);
if (pos > 0) {
p->lchild = build(pre_str.substr(1, pos), in_str.substr(0, pos), pos);
}
if (len-pos-1 > 0) {
p->rchild = build(pre_str.substr(pos+1), in_str.substr(pos+1), len-pos-1);
}
return p;
}
};
class BinaryTree {
private:
Node *root;
public:
BinaryTree() {
root = NULL;
}
~BinaryTree() {
if (root != NULL) {
delete root;
}
}
BinaryTree(const string &pre_str, const string &in_str, int len) {
root = root->build(pre_str, in_str, len);
}
void postorder() {
root->postorder();
}
};
int main() {
string pre_str = "136945827";
string in_str = "963548127";
BinaryTree binarytree(pre_str, in_str, in_str.length());
binarytree.postorder();
cout << endl;
return 0;
}
0 0
- 六、树和二叉树--(3)已知先序遍历和中序遍历求后序遍历
- 已知先序遍历和中序遍历求后序遍历——二叉树
- 已知先序遍历和中序遍历求后序遍历——二叉树
- 已知二叉树的先序遍历和中序遍历,如何求后序遍历
- java实现二叉树已知先序遍历和中序遍历求后序遍历
- 已知二叉树的先序和中序遍历,求后序遍历及二叉树
- 二叉树已知先序遍历和中序遍历得到后序遍历
- 已知先序遍历和中序遍历求后序遍历
- 已知先序遍历和中续遍历求后序遍历
- 已知先序遍历和中序遍历,求后序遍历 && 求二叉树中节点的最大距离
- 二叉树系列(一):已知先序遍历序列和中序遍历序列,求后序遍历序列
- 建立二叉树(已知中序遍历和先序遍历)
- 已知中序遍历和先序遍历重建二叉树
- 已知先序遍历和中序遍历求解二叉树
- 已知先序遍历和中序遍历构建二叉树
- 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
- 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
- 已知二叉树的前序遍历和中序遍历求后序遍历(二叉树)
- 引用传递和值传递
- 初学爬虫,爬取糗百段子(修改版,亲测)
- 使用Java实战RDD和DataFrame转换操作
- hdu 4706 Children's Day
- 逻辑的力量
- 六、树和二叉树--(3)已知先序遍历和中序遍历求后序遍历
- Mysql使用注意问题
- Collection(practice)
- 我爱学Java之Thread中stop(),suspend(),resume()为什么不安全
- 80. Remove Duplicates from Sorted Array II
- 草稿
- pull解析
- android客户端和php服务简单交互
- 【Leetcode】:22. Generate Parentheses 问题 in Go语言