贴一下代码。
定义:
struct BiNode{
string data;
BiNode* lchild, * rchild;
};
typedef BiNode* BiTree;
初始化:
int InitBiTree(BiTree& T){
T = NULL;
return 0;
}
根据前序遍历建二叉树(节点数据为‘#’表示为空节点):
char* CreateBiTree(BiTree& T, char* str)
{
// 约定#表示空结点
if (*str == '#')
{
T = NULL;
return str + 1;
}
// 创建结点
T = new BiNode;
T->data = *str;
// 继续输入并构造左子树和右子树
char* strAfterLeft = CreateBiTree(T->lchild, str + 1);
char* strAfterRight = CreateBiTree(T->rchild, strAfterLeft);
// 返回剩余的字符串
return strAfterRight;
}
前序遍历二叉树:
//递归
int PreTraverse(BiTree T) {
if (T == NULL) return 0;
cout << T->data;
PreTraverse(T->lchild);
PreTraverse(T->rchild);
return 0;
}
//非递归
string PreTraverse_nonRec(BiTree T)
{
// please write your code here
string result = "";
stack<BiNode*> S;
BiNode* p = T;
while (p || S.size()) {
while (p) {
result += p->data;
S.push(p);
p = p->lchild;
}
if (S.size()) {
p = S.top();
S.pop();
p = p->rchild;
}
}
return result;
}
中序遍历二叉树:
//递归
int InTraverse(BiTree T) {
if (T == NULL) return 0;
InTraverse(T->lchild);
cout << T->data;
InTraverse(T->rchild);
return 0;
}
//非递归
string InTraverse_nonRec(BiTree T)
{
// please write your code here
string result = "";
stack<BiNode*> S;
BiNode* p = T;
while (p || S.size()) {
while (p) {
S.push(p);
p = p->lchild;
}
if (S.size()) {
p = S.top();
S.pop();
result += p->data;
p = p->rchild;
}
}
return result;
}
后序遍历二叉树:
//递归
int SucTraverse(BiTree T) {
if (T == NULL) return 0;
SucTraverse(T->lchild);
SucTraverse(T->rchild);
cout << T->data;
return 0;
}
//非递归
string SucTraverse_nonRec(BiTree T)
{
// please write your code here
string result = "";
stack<BiNode*> S;
BiNode* p = T;
while (p || S.size()) {
while (p) {
result.insert(0, p->data);
S.push(p);
p = p->rchild;
}
if (S.size()) {
p = S.top();
S.pop();
p = p->lchild;
}
}
return result;
}
层次遍历二叉树:
string LevelTraverse(BiTree T) {
string s = "";
if (T) {
queue<BiTree> q;
q.push(T);
while (q.size()) {
auto t = q.front();
q.pop();
s += t->data;
if (t->lchild) q.push(t->lchild);
if (t->rchild) q.push(t->rchild);
}
}
return s;
}
前序遍历加中序遍历还原二叉树:
BiTree CreateBiTree(const char* pre, const char* mid, int n) {
BiTree T = new BiNode;
T->data = *pre;
int position = -1;
for (int i = 0; i < n; i++) {
if (mid[i] == *pre) position = i;
}
T->lchild = CreateBiTree(pre + 1, mid, position);
T->rchild = CreateBiTree(pre + 1 + position, mid + 1 + position, n - position - 1);
return T;
}