C语言二叉树类似DFS的先序遍历

已知图的深度优先搜索类似于二叉树的先序遍历,请根据非递归DFS算法,写出下列二叉树先序遍历非递归算法的函数体。注意:先序遍历的结点次序应与递归形式算法的结点次序完全一样。
void PreOrder_NonRecursive(BiTree root)
{ SeqStack S; BiTree p; //不能再定义新变量
if (root==NULL) return;
InitStack(&S); Push(&S,root);
while()

非递归DFS算法如下:

img

参考链接:
http://t.csdn.cn/44fFq


void preorder(bitree *t)//前序遍历的非递归算法
{
 bitree *temp = t;//定义一个树节点,用它来遍历
 while(temp != NULL || s.top != 0)
 {
  while(temp != NULL)//先遍历左孩子,并输出。
  {
   printf("%4d",temp->data);
   push(temp);
   temp = temp->lchild;
  }
  if(s.top != 0)//当左孩子遍历完后,取栈顶,找右孩子。此时循环还没有结束,再遍历它的左孩子,直至孩子全部遍历结束。
  {
   temp = pop();
   temp = temp->rchild;
  }
 }
 printf("\n");
}

希望对大佬有帮助。

void PreOrder_NonRecursive(BiTree root) {
    SeqStack S;
    BiTree p; //不能再定义新变量
    if (root==NULL) return;
    InitStack(&S);
    Push(&S,root);
    while(!IsEmpty(S)) {
        Pop(&S,&v);
        visit(v);
        if(v.rchild) Push(&S,v.rchild);
        if(v.lchild) Push(&S,v.lcchild);
    }
}

二叉树(前序遍历,dfs)

#include<iostream>
#include<map>
#include<cstdio>
using namespace std;
struct node{
    int left;
    int right;
};
node tree[1000005];
int n;
string str;
char t;
void dfs(int node){
    if(node+'0'=='*'){
        return;
    }
    printf("%c",node+'0');
    dfs(tree[node].left);
    dfs(tree[node].right);
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>str;
        if(i==0){
            t=str[0];
        }
        tree[str[0]-'0'].left=str[1]-'0';
        tree[str[0]-'0'].right=str[2]-'0';
    }
    dfs(t-'0');
    return 0;
}


参考一下

参考