数据结构之用堆栈模拟递归

 1 /*以中序序列为例,以BinTree为指针类型*/
 2 void InorderTraversal (BinTree BT)
 3 {
 4     BinTree T=BT;//从二叉树的头结点开始;
 5     Stack S = CreateStack();//创建一个堆栈;
 6     while (T || !Isempty(S))//当树不为空或堆栈不为空时继续;只有当都为空时才退出;
 7     {
 8         while (T)
 9         {
10             push (T);
11             T=T->Left;
12         }
13         if (!Isempty(S))
14         {
15             T=pop (S);//能从上面的while循环出来说明左子树走完了,想走右子树,这时必须拿出压栈的节点了;
16             printf ("%d",T->Data);
17             T=T->Right;
18         }
19     }
20 }
21 /*以先序序列为例*/
22 void InorderTraversal (BinTree BT)
23 {
24     BinTree T=BT;//从二叉树的头结点开始;
25     Stack S = CreateStack();//创建一个堆栈;
26     while (T || !Isempty(S))
27     {
28         while (T)
29         {
30             push(T);
31             printf ("%d",T->Data);
32             T=T->Left;
33         }
34         if (!Isempty(S))
35         {
36             T=pop(S);
37             T=T->Right;
38         }
39     }
40 }
41 /*以后序序列为例*/
42 void InorderTraversal (BinTree BT)
43 {
44     BinTree T=BT,temp=NULL;//从二叉树的头结点开始;temp是用来跟踪标记最近删除的节点;
45     Stack S = CreateStack();//创建一个堆栈;
46     while (T || !Isempty(S))
47     {
48         while (T)
49         {
50             push(T);
51             T=T->Left;
52         }
53         if (!Isempty(S))//能从上面的while循环出来说明左子树走完了,想走右子树;
54         {
55             T=top(S);//访问堆栈顶部元素;
56             if (T->Right && T->Right!=temp)//如果右子树存在,且未被访问过,那么父节点存在才有意义;
57             {
58                 T=T->Right;
59             }
60             else
61             {
62                 T=pop(T);
63                 temp=T;//temp是用来跟踪标记最近删除的节点;
64                 printf ("%d",T->Data);
65                 T=NULL;//让T=NULL好让T=top(S)实行;
66             }
67         }
68     }
69 }

以上是二叉树的非递归遍历,一个大佬的博客给了我很大的启发:https://blog.csdn.net/weixin_44462351/article/details/105693958?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-1-105693958.pc_agg_new_rank&utm_term=%E9%9D%9E%E9%80%92%E5%BD%92%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E7%9A%84%E6%80%9D%E6%83%B3&spm=1000.2123.3001.4430

还有一个层序遍历,其实就是广度优先搜索的方法,在浙大的p115;

posted @ 2022-02-07 18:57  次林梦叶  阅读(119)  评论(0)    收藏  举报