已知二叉树的先序遍历序列和中序遍历序列,求后序遍历序列。
先递归构造二叉树,然后递归得到后序序列。
思路:
先序序列的第一个结点为要构造二叉树的根结点,在中序序列中查找二叉树的根结点,则中序列根结点左边为根结点的左子树的中序序列,右边为根结点的右子树的中序序列。而先序序列根结点后面分别为它的左子树和右子树的先序序列。有了根结点在中序序列的位置,就知道了左子树和右子树的先序序列各自的位置。这样,就知道了根结点两个子树的序列。
然后在构造了根结点后,就可以递归调用函数来勾结根结点的左子树和右子树。
以上为二叉树的恢复。
后序遍历二叉树也是用递归即可。
代码如下:
string.find() 返回查找元素的下标
string.substr(a, b) 从第a个下标的元素开始截取b个元素
代码如下:
#include<iostream> #include<cstdio> #include<string> using namespace std; struct Node { char data; Node * lchild; Node * rchild; }; Node* CreatTree(string pre, string in) { Node * root = NULL; //树的初始化 if(pre.length() > 0) { root = new Node; //为根结点申请结构体所需要的内存 root->data = pre[0]; //先序序列的第一个元素为根结点 int index = in.find(root->data); //查找中序序列中的根结点位置 root->lchild = CreatTree(pre.substr(1, index), in.substr(0, index)); //递归创建左子树 root->rchild = CreatTree(pre.substr(index + 1), in.substr(index + 1)); //递归创建右子树 } return root; } void PostOrder(Node * root) //递归后序遍历 { if(root != NULL) { PostOrder(root->lchild); PostOrder(root->rchild); cout<<root->data; } } int main() { string pre_str, in_str; Node *root; while(cin>>pre_str>>in_str) { root = CreatTree(pre_str, in_str); PostOrder(root); cout<<endl; } return 0; }
本文介绍如何从已知的二叉树先序和中序遍历序列中,通过递归构造二叉树并获取其后序遍历序列的方法。文章提供了完整的C++实现代码。
1325

被折叠的 条评论
为什么被折叠?



