实现二叉树先序,中序和后序遍历
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
输入描述:
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输出描述:
输出三行,分别表示二叉树的先序,中序和后序。
示例1
输入
3 1
1 2 3
2 0 0
3 0 0
输出
1 2 3
2 1 3
2 3 1
备注:
1 ≤ n ≤ 1 0 6 1 \leq n \leq 10^6 1≤n≤106
1 ≤ r o o t , f a , l c h , r c h ≤ n 1 \leq root,fa,lch,rch \leq n 1≤root,fa,lch,rch≤n
题解:
先序遍历:根 左 右
中序遍历:左 根 右
后序遍历:左 右 根
先、中、后序遍历按照上面的顺序进行即可。此题如果使用递归,那就非常简单了。鉴于自己对递归转非递归一直未能掌握,此处使用非递归版本代码。稍微麻烦点的是中序遍历,但后续遍历非常麻烦。。。
#include <cstdio>
#include <stack>
using namespace std;
struct BST{
int val;
struct BST * lch, * rch;
BST() {}
BST(int v) : val(v), lch(NULL), rch(NULL) {}
};
void createTree(BST* root) {
int fa, lch, rch;
scanf("%d %d %d", &fa, &lch, &rch);
if (lch) {
root->lch = new BST(lch);
createTree(root->lch);
}
if (rch) {
root->rch = new BST(rch);
createTree(root->rch);
}
return;
}
void preorder(BST* root) {
if (!root) return;
stack<BST*> buff;
buff.push(root);
while (!buff.empty()) {
root = buff.top();
buff.pop();
printf("%d ", root->val);
if (root->rch) buff.push(root->rch);
if (root->lch) buff.push(root->lch);
}
puts("");
}
void inorder(BST* root) {
if (!root) return;
stack<BST*> buff;
while (!buff.empty() || root) {
if (root) {
buff.push(root);
root = root->lch;
} else {
root = buff.top();
buff.pop();
printf("%d ", root->val);
root = root->rch;
}
}
puts("");
}
void postorder(BST* root) {
if (!root) return;
stack<BST*> buff;
buff.push(root);
BST *tmp = NULL;
while (!buff.empty()) {
tmp = buff.top();
if (tmp->lch && root != tmp->lch && root != tmp->rch) {
buff.push(tmp->lch);
} else if (tmp->rch && root != tmp->rch) {
buff.push(tmp->rch);
} else {
printf("%d ", tmp->val);
buff.pop();
root = tmp;
}
}
puts("");
}
int main(void) {
int n, rt;
scanf("%d%d", &n, &rt);
BST* root = new BST(rt);
createTree(root);
preorder(root);
inorder(root);
postorder(root);
return 0;
}