HDU 4041 Eliminate Witches! (ACM ICPC 2011北京赛区网络赛)(二)
1
wuzetian
3
nanoha
fate
hayate
1 2
2 3
3 2
2 1
Source
The 36th ACM/ICPC Asia Regional Beijing Site —— Online Contest
Recommend
lcy
题目大意:T组测试数据,接下来T组字符串,表示一棵树,从字符串看树的结构显而易见,然后输出这棵树访问的过程。
解题思路:模拟题,这题就是一种先序的方式,但是不是二叉树,所以自己写程序模拟一下过程就可以了
#include#include #include #include #include
1)前序遍历
a)递归方式:
void preorder_recursive(Bitree T) /* 先序遍历二叉树的递归算法 */
{
if (T) {
visit(T); /* 访问当前结点 */
preorder_recursive(T->lchild); /* 访问左子树 */
preorder_recursive(T->rchild); /* 访问右子树 */
}
}
b)非递归方式
void preorder_nonrecursive(Bitree T) /* 先序遍历二叉树的非递归算法 */
{
initstack(S);
push(S,T); /* 根指针进栈 */
while(!stackempty(S)) {
while(gettop(S,p)&&p) { /* 向左走到尽头 */
visit(p); /* 每向前走一步都访问当前结点 */
push(S,p->lchild);
}
pop(S,p);
if(!stackempty(S)) { /* 向右走一步 */
pop(S,p);
push(S,p->rchild);
}
}
}
2)中序遍历
a)递归方式
void inorder_recursive(Bitree T) /* 中序遍历二叉树的递归算法 */
{
if (T) {
inorder_recursive(T->lchild); /* 访问左子树 */
visit(T); /* 访问当前结点 */
inorder_recursive(T->rchild); /* 访问右子树 */
}
}
b)非递归方式
void inorder_nonrecursive(Bitree T)
{
initstack(S); /* 初始化栈 */
push(S, T); /* 根指针入栈 */
while (!stackempty(S)) {
while (gettop(S, p) && p) /* 向左走到尽头 */
push(S, p->lchild);
pop(S, p); /* 空指针退栈 */
if (!stackempty(S)) {
pop(S, p);
visit(p); /* 访问当前结点 */
push(S, p->rchild); /* 向右走一步 */
}
}
}
3)后序遍历
a)递归方式
void postorder_recursive(Bitree T) /* 中序遍历二叉树的递归算法 */
{
if (T) {
postorder_recursive(T->lchild); /* 访问左子树 */
postorder_recursive(T->rchild); /* 访问右子树 */
visit(T); /* 访问当前结点 */
}
}
b)非递归方式
typedef str
| 评论 |
|
|