二叉树遍历输出
按先序遍历序列建立一个二叉树的二叉链表,并按先序遍历、中序遍历、后序遍历将其输出。
测试输入1
-+a##*b##c##/d##e##↵
期待的输出1
前序遍历结果:- + a * b c / d e ↵
中序遍历结果:a + b * c - d / e ↵
后序遍历结果:a b c * + d e / - ↵
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int max(int a, int b)
{
if (a >= b)
return a;
else
return b;
}
class binarytreenode {
public:
char data;
binarytreenode * Lchild, * Rchild;
binarytreenode() { Lchild = NULL; Rchild = NULL; }
};
class binarytree {
public:
binarytreenode * root;
binarytree() { root =NULL; }
void createtree( binarytreenode * &p)
{
char ch;
cin >> ch;
if (ch == '\n')
return;
if (ch == '#')
p = NULL;
else
{
p = new binarytreenode();
if (!p)
exit(-1);
p->data = ch;
createtree(p->Lchild);
createtree(p->Rchild);
return;
}
}
int depth(binarytreenode *p)
{
if (p == NULL)
return 0;
else
return 1 + max(depth(p->Lchild), depth(p->Rchild));
}
int leaf(binarytreenode *p)
{
if (p == NULL) return 0;
if (p->Lchild == NULL && p->Rchild == NULL)
return 1;
if (p == NULL)
return -1;
else
{
return 0 + leaf(p->Lchild) + leaf(p->Rchild);
}
}
void dlr(binarytreenode *p)
{
if (p != NULL)
{
cout << p->data<<' ';
dlr(p->Lchild);
dlr(p->Rchild);
}
}
void ldr(binarytreenode *p)
{
if (p != NULL)
{
ldr(p->Lchild);
cout << p->data<<' ';
ldr(p->Rchild);
}
}
void lrd(binarytreenode *p)
{
if (p != NULL)
{
lrd(p->Lchild);
lrd(p->Rchild);
cout <<p->data<<' ';
}
}
};
bool similar(binarytreenode *t1, binarytreenode *t2)
{
bool leftS = false, rightS = false;
if (t1 == NULL && t2 == NULL) // 两树皆空
return true;
else if (t1 == NULL || t2 == NULL) // 只有一个树为空
return false;
else // 递归地进行判断
{
leftS = similar(t1->Lchild, t2->Lchild);
rightS = similar(t1->Rchild, t2->Rchild);
return leftS && rightS;
}
}
int main()
{
binarytree x, t;
x.createtree(x.root);
cout <<"前序遍历结果:";
x.dlr(x.root);
cout << endl;
cout << "中序遍历结果:" ;
x.ldr(x.root);
cout << endl;
cout << "后序遍历结果:" ;
x.lrd(x.root);
cout << endl;
return 0;
}