简便构造二叉树
文章目录
1二叉树的三种遍历
二叉树结构:
struct node
{
char data;
node *l,*r;
};
1.1前序遍历
遍历顺序:
- 访问根节点
- 遍历左子树
- 遍历右子树
代码:
void preorder(node * p)
{
if(p == NULL)
return;
cout<<p->data;//访问根节点
preorder(p->l);//遍历左子树
preorder(p->r);//遍历右子树
}
1.2中序遍历
遍历顺序:
- 遍历左子树
- 访问根节点
- 遍历右子树
代码:
void inorder(node * p)
{
if(p == NULL)
return;
inorder(p->l);//遍历左子树
cout<<p->data;//访问根节点
inorder(p->r);//遍历右子树
}
1.3后序遍历
遍历顺前序:
- 遍历左子树
- 遍历右子树
- 访问根节点
代码:
void postorder(node * p)
{
if(p == NULL)
return;
postorder(p->l);//遍历左子树
postorder(p->r);//遍历右子树
cout<<p->data;//访问根节点
}
1.4小结
三种遍历的代码很容易根据对应的规则写出,无非就是访问根节点的时机不同,根节点在最开始访问的为前序,中间访问为中序,最后访问为后序。
前序:1,2,4,5,3
中序:4,2,5,1,3
后序:4,5,2,3,1
2构造二叉树
掌握了二叉树的三种遍历之后,利用其构造二叉树就很容易了。
通过观察可发现:
- 前序遍历中,第一个节点为根节点
- 后序遍历中,最后一个节点为根节点
- 中序遍历中,根节点左半部分为左子树,右半部分为右子树
同样的,构造二叉树同样可以利用递归来构造,只需要找到根节点,再分别构造左子树和右子树即可。
那么问题来了,已知前序和后序能否构造二叉树呢?答案是不能的,因为没有中序遍历就无法确定左右子树,所以仅通过前序和后序无法构造唯一二叉树。
2.1已知前序中序
如图1所示,
前序:1 2 4 5 3
中序:4 2 5 1 3
由前序知,根节点为1,则左子树为4 2 5,右子树为3。
在树4 2 5中,由前序知,根节点为2,则左子树为4,右子树为3。
经过一系列递归,最后成功构造二叉树。
代码:
#include <iostream>
#include <string>
using namespace std;
string pre,in,post;
node* root;
node* rebuild(string pre,string in)
{
if(in.size()<=0)
return NULL;
node * p = new node();
char c = pre[0];
int k=in.find(c);
p->data = c;
p->l = rebuild(pre.substr(1,k+1),in.substr(0,k));
p->r = rebuild(pre.substr(k+1),in.substr(k+1));
return p;
}
int main()
{
cin>>pre>>in;
root = rebuild(pre,in);
return 0;
}
2.2已知中序后序
代码:
#include <iostream>
#include <string>
using namespace std;
string pre,in,post;
node* root;
node* rebuild(string in,string post)
{
if(in.size()<=0)
return NULL;
node * p = new node();
char c = post[post.size()-1];
int k=in.find(c);
p->data = c;
p->l = rebuild(in.substr(0,k),post.substr(0,k));
p->r = rebuild(in.substr(k+1),post.substr(k,in.size()-k-1));
return p;
}
int main()
{
cin>>in>>post;
root = rebuild(in,post);
return 0;
}
3已知两序求第三序
掌握了规律后,已知其中两种顺序,再求另一种顺序,就不用构造二叉树后再遍历,直接就可求出。
3.1已知前序中序求后序
代码:
#include <iostream>
#include <string>
using namespace std;
string pre,in,post;
void rec(string pre,string in)
{
if(in.size()<=0)
return;
char c = pre[0];
int k=in.find(c);
rec(pre.substr(1,k+1),in.substr(0,k));
rec(pre.substr(k+1),in.substr(k+1));
cout<<c;
}
int main()
{
cin>>pre>>in;
rec(pre,in);
return 0;
}
3.2已知中序后序求前序
代码:
#include <iostream>
#include <string>
using namespace std;
string pre,in,post;
void rec(string in,string post)
{
if(in.size()<=0)
return;
char c = post[post.size()-1];
int k=in.find(c);
cout<<c;
rec(in.substr(0,k),post.substr(0,k));
rec(in.substr(k+1),post.substr(k,in.size()-k-1));
}
int main()
{
cin>>in>>post;
rec(in,post);
return 0;
}