”算法:用堆栈实现
创建堆栈
把根节点压入堆栈
当堆栈不为空时,循环
弹出一个节点
如果这个节点不是NULL
输出该值
把这个节点的右节点压入堆栈
把这个节点的左节点压入堆栈
void PreOderTranversal(node *root)
{
element *TheStack;
void *data;
node *CurNode;
CreateStack(&TheStack);
Push(&TheStack, root);
while(Pop(&TheStack, &data)){
CurNode = (node *)data;
if(CurNode){
printf("%d/n", CurNode->value);
Push(&TheStack, CurNode->right);
Push(&TheStack, CurNode->left);
}
}
DeleteStack(&TheStack);
}
其实还不大完善,不过问题已经不大了。这么简单的问题,让我给想得忒复杂.......郁闷,看来我的思维能力还是有所欠缺啊
后记:现在我给出一个比较完善的程序:
/*不用递归先序遍历一棵树,并把其节点组成一个单向链表*/
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
struct _Node {
_Node *next;
};
struct _Tree {
_Tree *left;
_Tree *right;
};
_Node *MakeList(_Tree *root)
{
stack<_Tree*> sk;
_Node *head = NULL;
_Tree *tmp;
_Node *current,*news;
head = new _Node;
head = (_Node*)root;
head->next = NULL;
current = head;
sk.push(root);
while ( !sk.empty() ) {
tmp = sk.top();
sk.pop();
if (tmp != root) {
news = new _Node;
current->next = news;
news->next = NULL;
current = news;
news = (_Tree*)tmp;
}
if (tmp->right != NULL)
sk.push(tmp->right);
else if (tmp->left != NULL)
sk.push(tmp->left);
}
return head;
}
”
这里发现左结点压栈之后马上又出栈,所以可以进一步简化成如下结构:
push(root);
while(stack is not empty){
pop(p);
while(p!=null){
visit(p);
push(p->rchild);
p=p->lchild;
}
}