最近在复习二叉树的算法,所以对二叉树的遍历分别做了用两中不同方式来实现二叉树遍历
首先是先序遍历
1 /***********************先序遍历**************************/ 2 //先输出当前结点,再输出左结点,再输出右结点 3 4 /// <summary> 5 /// 使用非递归方式实现先序遍历 6 /// </summary> 7 /// <param name="head"></param> 8 public static void PreOrderUnRecur(Node head) 9 { 10 //保证这个结点不为空 11 if (head != null) 12 { 13 Stack<Node> stack = new Stack<Node>(); 14 //将结点压栈 15 stack.Push(head); 16 //循环将当前结点弹出并输出,然后压栈,先加右结点,再加左结点 17 //这是为了保证下一个弹出的是左结点 例如弹出了A,然后压入C,再压入B 18 //下个弹出的就会是B,然后依次循环直至没东西 19 while (stack.Count != 0) 20 { 21 head = stack.Pop(); 22 Console.Write(head.value + " "); 23 if (head.right != null) 24 { 25 stack.Push(head.right); 26 } 27 if (head.left != null) 28 { 29 stack.Push(head.left); 30 } 31 } 32 } 33 } 34 35 /// <summary> 36 /// 使用递归实现先序遍历 37 /// </summary> 38 /// <param name="head"></param> 39 public static void PreOrderUnRecurs(Node head) 40 { 41 if (head == null) return; 42 Console.Write(head.value + " "); 43 PreOrderUnRecurs(head.left); 44 PreOrderUnRecurs(head.right); 45 }
接着是中序遍历
1 /***********************中序遍历**************************/
2 //先遍历输出左结点,再输出当前结点,最后输出右结点
3
4 /// <summary>
5 /// 中序遍历
6 /// </summary>
7 /// <param name="head"></param>
8 public static void InOrderUnRecur(Node head)
9 {
10 if (head != null)
11 {
12 Stack<Node> stack = new Stack<Node>();
13 //将首节点先入栈,然后将他一直赋值成他的左孩子,直到没有左孩子了
14 //就输出当前结点,然后回到栈顶,弹出数据并输出
15 //然后将结点变成右结点,保证找到所有右结点
16 while (stack.Count != 0 || head != null)
17 {
18 if (head != null)
19 {
20 stack.Push(head);
21 head = head.left;
22 }
23 else
24 {
25 head = stack.Pop();
26 Console.Write(head.value + " ");
27 head = head.right;
28 }
29 }
30 }
31 }
32
33 /// <summary>
34 /// 中序遍历
35 /// </summary>
36 /// <param name="head"></param>
37 public static void InOrderUnRecurDG(Node head)
38 {
39 if (head == null) return;
40 InOrderUnRecurDG(head.left);
41 Console.Write(head.value + " ");
42 InOrderUnRecurDG(head.right);
43 }
最后是后序遍历
1 /***********************后序遍历**************************/ 2 //先遍历输出左结点,再输出右结点,最后再输出当前结点 3 4 /// <summary> 5 /// 使用两个栈实现 6 /// </summary> 7 /// <param name="head"></param> 8 public static void PosOrderUnRecurl(Node head) 9 { 10 if (head != null) 11 { 12 Stack<Node> s1 = new Stack<Node>(); 13 Stack<Node> s2 = new Stack<Node>(); 14 //先将结点压入s1 15 s1.Push(head); 16 //循环遍历弹出s1的栈顶数据cu,将他的左右孩子加入s1 17 //然后将cu加入s2,直到s1为空,输出s2的数据 18 while (s1.Count != 0) 19 { 20 head = s1.Pop(); 21 s2.Push(head); 22 if (head.left != null) 23 { 24 s1.Push(head.left); 25 } 26 27 if (head.right != null) 28 { 29 s1.Push(head.right); 30 } 31 } 32 33 while (s2.Count != 0) 34 { 35 Console.Write(s2.Pop().value + " "); 36 } 37 } 38 } 39 40 /// <summary> 41 /// 使用递归实现后序遍历 42 /// </summary> 43 /// <param name="head"></param> 44 public static void PosOrderUnRecur2(Node head) 45 { 46 if (head == null) return; 47 PosOrderUnRecur2(head.left); 48 PosOrderUnRecur2(head.right); 49 Console.Write(head.value + " "); 50 }