C # traverse the binary tree in sequence (non-recursion ),
I found the next step to traverse Binary Tree C #. The implementation seems to be less satisfactory.
The general idea is:
Input the root node and push its subnodes to the stack in turn,
When the pushed nodes do not have subnodes (leaves) or all subnodes have been traversed (the last traversal node is the right subnode of the node), and then exit the stack in sequence.
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace ConsoleApplication5 8 {9 class Program 10 {11 static void Main (string [] args) 12 {13 Node treeRoot = CreateTree (); 14 scanTree (treeRoot ); 15} 16 17 private static void scanTree (Node treeRoot) 18 {19 List <Node> list = new List <Node> (); 20 list. add (treeRoot); 21 Node point = treeRoot; 22 Write (treeRoot); 23 while (true) 24 {25 if (! List. contains (point) 26 {// The last round is the removed operation 27 if (treeRoot. leftSon = point) 28 {// remove the left node 29 if (treeRoot. rightSon! = Null) 30 {31 treeRoot = treeRoot. rightSon; 32 list. add (treeRoot); 33 Write (treeRoot); 34 point = treeRoot; 35 continue; 36} 37 list. remove (treeRoot); 38 if (list. count = 0) 39 {40 break; 41} 42 point = treeRoot; 43 treeRoot = list [list. count-1]; 44} 45 else 46 {// The right node 47 list is removed. remove (treeRoot); 48 if (list. count = 0) 49 {50 break; 51} 52 point = treeRoot; 53 treeRoot = list [list. coun T-1]; 54} 55 continue; 56} 57 58 if (treeRoot. leftSon! = Null) 59 {60 treeRoot = treeRoot. leftSon; 61 Write (treeRoot); 62 list. add (treeRoot); 63 point = treeRoot; 64 continue; 65} 66 if (treeRoot. rightSon! = Null) 67 {68 treeRoot = treeRoot. rightSon; 69 Write (treeRoot); 70 point = treeRoot; 71 list. add (treeRoot); 72 continue; 73} 74 // the current node is the leaf node if (treeRoot. leftSon = null & treeRoot. rightSon = null) 75 // {76 list. remove (treeRoot); 77 if (list. count = 0) 78 {79 break; 80} 81 point = treeRoot; 82 treeRoot = list [list. count-1]; 83 //} 84} 85 86} 87 88 public static void Write (Node node) 89 {90 Console. writeLine (node. data); 91} 92 93 private static Node CreateTree () 94 {95 Node a = new Node ("A"); 96. leftSon = new Node ("B"); 97. rightSon = new Node ("C"); 98 99. leftSon. leftSon = new Node ("D"); 100. leftSon. rightSon = new Node ("E"); 101 102. rightSon. leftSon = new Node ("F"); 103. rightSon. rightSon = new Node ("G"); 104 105. leftSon. leftSon. leftSon = new Node ("H"); 106. leftSon. leftSon. rightSon = new Node ("I"); 107 return a; 108} 109} 110 111 class Node112 {113 public string Data {get; set;} 114 public Node leftSon {get; set;} 115 public Node rightSon {get; set;} 116 117 public Node (string data) 118 {119 Data = data; 120} 121} 122}