文章
74
粉丝
0
获赞
98
访问
8.9k
例题:若一棵二叉树的前序遍历为 ABCDEF,中序遍历为 CBAEDF,请画出这棵二叉树。
分析:前序遍历第一个输出结点为根结点,故 A 为根结点。早中序遍历中根结点处于左右子树 结点中间,故结点 A 的左子树中结点有 CB,右子树中结点有 EDF。
tip:string.substr(idx, length); // idx表示开始分割的下标,length为切割的长度
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
char data;
struct node *lchild, *rchild;
}*BitTree;
void CreateBitTree(BitTree &T, string pre, string in){
if(pre == "") T = NULL;
else {
T = new node;
T->data = pre[0];
int idx = in.find(pre[0]); // 找到中序遍历字符串in中根节点下标
// 根据根节点划分中序遍历字符串in
string l_in = in.substr(0, idx);
string r_in = in.substr(idx + 1, in.length()-l_in.length()-1);
// 根据划分的中序遍历字符串in长度来划分前序遍历字符串pre
string l_pre = pre.substr(1, l_in.length());
string r_pre = pre.substr(l_pre.length()+1, r_in.length());
CreateBitTree(T->lchild, l_pre, l_in);
CreateBitTree(T->rchild, r_pre, r_in);
}
}
voi...
登录后发布评论
暂无评论,来抢沙发