Binary tree traversal

Source: Internet
Author: User

Binary tree traversal

There are three methods to traverse a binary tree:

(1) first traverse (DLR), first visit the root node, then traverse the left subtree, and finally traverse the right subtree. Note root-left-right.

(2) In the middle-order traversal (LDR), first traverse the left subtree, then access the root node, and finally traverse the right subtree. Note: Left-root-right.

(3) Post-sequential traversal (LRD): First traverse the left subtree, then traverse the right subtree, and finally access the root node. Note: Left-right-root.

Example 1: Binary Tree as shown in. If it is traversed in the forward order, the output sequence is. If it is traversed in the middle order, the output sequence is. If it is traversed in the descending order, the output sequence is.

Pre-order: Root A, left subtree B of A, and left subtree B does not. Look at right subtree, It is D, so A-B-D. Let's take A look at the right subtree of A, root C, left subtree E, left subtree F of E, right subtree G of E, and left subtree H of G. Connect to the C-E-F-G-H and the final result is ABDCEFGH

In the middle order: first access the left subtree of the root, B does not have the left subtree, it has the right subtree D, D does not have the left subtree, and the root A of the access tree below is connected to the slave.

Then access the right subtree of the root. The left subtree of C is F, the root of F is E, and the right subtree of E has the left subtree is H, find G from H, end the left subtree of C, and find the root C, no right subtree, and end. The link is FEHGC, and the intermediate result is BDAFEHGC.

Descending order: B has no left subtree, right subtree D, and then to root B. Let's look at the right subtree. The bottom left subtree is F, the right subtree of its root is H, then to the root G of H, and then to the root E of G, the root C of E has no right subtree and goes directly to C. Then, contact B for their root A, so DBFHGECA is connected.

Example 2: There are the following binary trees. The result of the forward traversal of this binary tree is ().

A) acbedgfh B) ABDGCEHF

C) hgfedcba d) ABCDEFGH

Resolution: root A first, left subtree first root B, B No left subtree, right subtree, root D first, in left subtree G, connected to ABDG. Right subtree of A, first rooted in C, C left subtree E, E without left subtree, right subtree with H, right subtree of C Only F, connected to CEHF. B's answer is ABDGCEHF.

Example 3: it is known that the binary tree's post-order traversal is DABEC, the middle-order traversal sequence is DEBAC, and its pre-order traversal sequence is ().

A) cedba B) ACBED C) DECAB D) DEABC

Resolution: It can be seen from the post-order traversal that C is the root node. It can be seen from the middle-order traversal that the Left subtree of C contains DEBA, and no knots on the Right of C, and no right subtree on the zhiroot node. First, traverse the root C in order. Only A starts with C in the answer, which is the correct answer.

The descending traversal is DABEC, and the middle traversal is DEBAC.

From the back-order traversal, we can see that C is the root node. When we see that the middle-order traversal is finally C, the root node does not have the right subtree. In the descending order of traversal from the back to the second is E, then the left subtree of the root node is E, combining two traversal, the first is D, then D is the leftmost subtree. It can be seen that the structure is C E D B

Example 4: the result of sequential traversal in a binary tree is ().

A). acbdfeg B). ACBDFGE C). ABDCGEF D). FCADBEG

Resolution: first, traversing the root in the middle order will separate the left and right subtree. F will not exclude C and D from the beginning and end of the answer. In the right subtree of F, G is the right subtree of E. In the middle traversal, access E first, then access G, and E is in front of G, excluding B. The answer is.

Example 5: The result of the following Binary Tree post-sequential traversal is ().

A) abcdef B) DBEAFC C) ABDECF D) DEBFCA

Resolution: the last post-order must be the root of a binary tree and the answer is D.


The chain storage structure of Binary Trees is an important type of data structure. Its format is defined as follows:

[Cpp]View plaincopy
  1. // Binary Tree node
  2. Typedef struct BiTNode {
  3. // Data
  4. Char data;
  5. // Left and right child pointer
  6. Struct BiTNode * lchild, * rchild;
  7. } BiTNode, * BiTree;


    Create a binary tree:

    By reading a string, the algorithm for creating a binary tree is as follows:

    [Cpp]View plaincopy
    1. // Create a binary tree in sequence
    2. Int CreateBiTree (BiTree & T ){
    3. Char data;
    4. // Enter the value of the node in the binary tree in the First Order (one character). '#' indicates the empty tree.
    5. Scanf ("% c", & data );
    6. If (data = '#'){
    7. T = NULL;
    8. }
    9. Else {
    10. T = (BiTree) malloc (sizeof (BiTNode ));
    11. // Generate the root node
    12. T-> data = data;
    13. // Construct the left subtree
    14. CreateBiTree (T-> lchild );
    15. // Construct the right subtree
    16. CreateBiTree (T-> rchild );
    17. }
    18. Return 0;
    19. }
      Binary tree traversal:

      Traversal is the most basic operation of a tree. The so-called traversal of a binary tree is to travel all nodes of the binary tree in a certain rule and order, so that each node is accessed once, and only once. Because the binary tree structure is non-linear, tree traversal essentially converts each node of the binary tree into a linear sequence for representation.

      Recursive Algorithm:

      [Cpp]View plaincopy
      1. // Output
      2. Void Visit (BiTree T ){
      3. If (T-> data! = '#'){
      4. Printf ("% c", T-> data );
      5. }
      6. }
      7. // First-order traversal
      8. Void PreOrder (BiTree T ){
      9. If (T! = NULL ){
      10. // Access the root node
      11. Visit (T );
      12. // Access the left subnode
      13. PreOrder (T-> lchild );
      14. // Access the right subnode
      15. PreOrder (T-> rchild );
      16. }
      17. }
      18. // Sequential Traversal
      19. Void InOrder (BiTree T ){
      20. If (T! = NULL ){
      21. // Access the left subnode
      22. InOrder (T-> lchild );
      23. // Access the root node
      24. Visit (T );
      25. // Access the right subnode
      26. InOrder (T-> rchild );
      27. }
      28. }
      29. // Post-order traversal
      30. Void PostOrder (BiTree T ){
      31. If (T! = NULL ){
      32. // Access the left subnode
      33. PostOrder (T-> lchild );
      34. // Access the right subnode
      35. PostOrder (T-> rchild );
      36. // Access the root node
      37. Visit (T );
      38. }
      39. }

        Non-recursive algorithms:

        <1> sequential traversal:

        [Idea]: After accessing T-> data, add T to the stack and traverse the left subtree. When the left subtree is returned, the top element of the stack should be T, and the stack is output, then, traverse the right subtree of T in sequence.

        [Cpp]View plaincopy
        1. /* First-order traversal (non-recursion)
        2. Idea: After accessing T-> data, T is added to the stack and the left subtree is traversed. When the left subtree is returned, the top element of the stack should be T, and the stack is output, then, traverse the right subtree of T in sequence.
        3. */
        4. Void PreOrder2 (BiTree T ){
        5. Stack Stack;
        6. // P is the traversal pointer
        7. BiTree p = T;
        8. // Loop when stack is not empty or p is not empty
        9. While (p |! Stack. empty ()){
        10. If (p! = NULL ){
        11. // Save to stack
        12. Stack. push (p );
        13. // Access the root node
        14. Printf ("% c", p-> data );
        15. // Traverse the left subtree
        16. P = p-> lchild;
        17. }
        18. Else {
        19. // Stack rollback
        20. P = stack. top ();
        21. Stack. pop ();
        22. // Access the right subtree
        23. P = p-> rchild;
        24. }
        25. } // While
        26. }


          <2> ordinal Traversal

          [Idea]: T is the root pointer of the tree to be traversed. The central traversal requires that the root be accessed after the left subtree is traversed, and then the right subtree be traversed.
          First, T is added to the stack and the left subtree is traversed. When the left subtree is returned, the top element of the stack should be T, and the stack is output. Access T-> data, traverse the right subtree of T in the middle order.

          [Cpp]View plaincopy
          1. Void InOrder2 (BiTree T ){
          2. Stack Stack;
          3. // P is the traversal pointer
          4. BiTree p = T;
          5. // Loop when stack is not empty or p is not empty
          6. While (p |! Stack. empty ()){
          7. If (p! = NULL ){
          8. // Save to stack
          9. Stack. push (p );
          10. // Traverse the left subtree
          11. P = p-> lchild;
          12. }
          13. Else {
          14. // Return to the stack and access the root node
          15. P = stack. top ();
          16. Printf ("% c", p-> data );
          17. Stack. pop ();
          18. // Access the right subtree
          19. P = p-> rchild;
          20. }
          21. } // While
          22. }
            <3> post-order traversal

            [Idea]: T is the root pointer of the tree to be traversed. Post-order traversal requires that the root be accessed after the left and right subtree is traversed. You need to determine whether the left and right subtree of the root node have been traversed.

            [Cpp]View plaincopy
            1. // Post-order traversal (non-recursion)
            2. Typedef struct BiTNodePost {
            3. BiTree biTree;
            4. Char tag;
            5. } BiTNodePost, * BiTreePost;
            6. Void PostOrder2 (BiTree T ){
            7. Stack Stack;
            8. // P is the traversal pointer
            9. BiTree p = T;
            10. BiTreePost BT;
            11. // Loop when stack is not empty or p is not empty
            12. While (p! = NULL |! Stack. empty ()){
            13. // Traverse the left subtree
            14. While (p! = NULL ){
            15. BT = (BiTreePost) malloc (sizeof (BiTNodePost ));
            16. BT-> biTree = p;
            17. // Access the left subtree
            18. BT-> tag = 'l ';
            19. Stack. push (BT );
            20. P = p-> lchild;
            21. }
            22. // Access the root node after the left and right subtree access is completed
            23. While (! Stack. empty () & (stack. top ()-> tag = 'R '){
            24. BT = stack. top ();
            25. // Stack rollback
            26. Stack. pop ();
            27. BT-> biTree;
            28. Printf ("% c", BT-> biTree-> data );
            29. }
            30. // Traverse the right subtree
            31. If (! Stack. empty ()){
            32. BT = stack. top ();
            33. // Access the right subtree
            34. BT-> tag = 'R ';
            35. P = BT-> biTree;
            36. P = p-> rchild;
            37. }
            38. } // While
            39. }


              <4> hierarchical Traversal

              [Idea]: access each node layer by layer in the order of top-down and left-right. A queue is required in the process of layered traversal.

              [Cpp]View plaincopy
              1. // Hierarchical Traversal
              2. Void LevelOrder (BiTree T ){
              3. BiTree p = T;
              4. // Queue
              5. Queue Queue;
              6. // Enter the root node
              7. Queue. push (p );
              8. // The queue is not empty.
              9. While (! Queue. empty ()){
              10. // The opponent element leaves the queue
              11. P = queue. front ();
              12. // Access the node pointed to by p
              13. Printf ("% c", p-> data );
              14. // Exit the queue
              15. Queue. pop ();
              16. // Leave the left subtree empty.
              17. If (p-> lchild! = NULL ){
              18. Queue. push (p-> lchild );
              19. }
              20. // Enter the right subtree if it is not empty.
              21. If (p-> rchild! = NULL ){
              22. Queue. push (p-> rchild );
              23. }
              24. }
              25. }

                Test cases:


                Input:

                ABC ## DE # G ## F ###

                Output:


                Code:

                [Cpp]View plaincopy
                1. # Include
                2. # Include
                3. # Include
                4. Using namespace std;
                5. // Binary Tree node
                6. Typedef struct BiTNode {
                7. // Data
                8. Char data;
                9. // Left and right child pointer
                10. Struct BiTNode * lchild, * rchild;
                11. } BiTNode, * BiTree;
                12. // Create a binary tree in sequence
                13. Int CreateBiTree (BiTree & T ){
                14. Char data;
                15. // Enter the value of the node in the binary tree in the First Order (one character). '#' indicates the empty tree.
                16. Scanf ("% c", & data );
                17. If (data = '#'){
                18. T = NULL;
                19. }
                20. Else {
                21. T = (BiTree) malloc (sizeof (BiTNode ));
                22. // Generate the root node
                23. T-> data = data;
                24. // Construct the left subtree
                25. CreateBiTree (T-> lchild );
                26. // Construct the right subtree
                27. CreateBiTree (T-> rchild );
                28. }
                29. Return 0;
                30. }
                31. // Output
                32. Void Visit (BiTree T ){
                33. If (T-> data! = '#'){
                34. Printf ("% c", T-> data );
                35. }
                36. }
                37. // First-order traversal
                38. Void PreOrder (BiTree T ){
                39. If (T! = NULL ){
                40. // Access the root node
                41. Visit (T );
                42. // Access the left subnode
                43. PreOrder (T-> lchild );
                44. // Access the right subnode
                45. PreOrder (T-> rchild );
                46. }
                47. }
                48. // Sequential Traversal
                49. Void InOrder (BiTree T ){
                50. If (T! = NULL ){
                51. // Access the left subnode
                52. InOrder (T-> lchild );
                53. // Access the root node
                54. Visit (T );
                55. // Access the right subnode
                56. InOrder (T-> rchild );
                57. }
                58. }
                59. // Post-order traversal
                60. Void PostOrder (BiTree T ){
                61. If (T! = NULL ){
                62. // Access the left subnode
                63. PostOrder (T-> lchild );
                64. // Access the right subnode
                65. PostOrder (T-> rchild );
                66. // Access the root node
                67. Visit (T );
                68. }
                69. }
                70. /* First-order traversal (non-recursion)
                71. Idea: After accessing T-> data, T is added to the stack and the left subtree is traversed. When the left subtree is returned, the top element of the stack should be T, and the stack is output, then, traverse the right subtree of T in sequence.
                72. */
                73. Void PreOrder2 (BiTree T ){
                74. Stack Stack;
                75. // P is the traversal pointer
                76. BiTree p = T;
                77. // Loop when stack is not empty or p is not empty
                78. While (p |! Stack. empty ()){
                79. If (p! = NULL ){
                80. // Save to stack
                81. Stack. push (p );
                82. // Access the root node
                83. Printf ("% c", p-> data );
                84. // Traverse the left subtree
                85. P = p-> lchild;
                86. }
                87. Else {
                88. // Stack rollback
                89. P = stack. top ();
                90. Stack. pop ();
                91. // Access the right subtree
                92. P = p-> rchild;
                93. }
                94. } // While
                95. }
                96. /* Sequential traversal (non-recursion)
                97. Idea: T is the root pointer of the tree to be traversed. The central traversal requires that after the left subtree is traversed, the root is accessed and then the right subtree is traversed.
                98. First, T is added to the stack and the left subtree is traversed. When the left subtree is returned, the top element of the stack should be T, and the stack is output. Access T-> data, traverse the right subtree of T in the middle order.
                99. */
                100. Void InOrder2 (BiTree T ){
                101. Stack Stack;
                102. // P is the traversal pointer
                103. BiTree p = T;
                104. // Loop when stack is not empty or p is not empty
                105. While (p |! Stack. empty ()){
                106. If (p! = NULL ){
                107. // Save to stack
                108. Stack. push (p );
                109. // Traverse the left subtree
                110. P = p-> lchild;
                111. }
                112. Else {
                113. // Return to the stack and access the root node
                114. P = stack. top ();
                115. Printf ("% c", p-> data );
                116. Stack. pop ();
                117. // Access the right subtree
                118. P = p-> rchild;
                119. }
                120. } // While
                121. }
                122. // Post-order traversal (non-recursion)
                123. Typedef struct BiTNodePost {
                124. BiTree biTree;
                125. Char tag;
                126. } BiTNodePost, * BiTreePost;
                127. Void PostOrder2 (BiTree T ){
                128. Stack Stack;
                129. // P is the traversal pointer
                130. BiTree p = T;
                131. BiTreePost BT;
                132. // Loop when stack is not empty or p is not empty
                133. While (p! = NULL |! Stack. empty ()){
                134. // Traverse the left subtree
                135. While (p! = NULL ){
                136. BT = (BiTreePost) malloc (sizeof (BiTNodePost ));
                137. BT-> biTree = p;
                138. // Access the left subtree
                139. BT-> tag = 'l ';
                140. Stack. push (BT );
                141. P = p-> lchild;
                142. }
                143. // Access the root node after the left and right subtree access is completed
                144. While (! Stack. empty () & (stack. top ()-> tag = 'R '){
                145. BT = stack. top ();
                146. // Stack rollback
                147. Stack. pop ();
                148. BT-> biTree;
                149. Printf ("% c", BT-> biTree-> data );
                150. }
                151. // Traverse the right subtree
                152. If (! Stack. empty ()){
                153. BT = stack. top ();
                154. // Access the right subtree
                155. BT-> tag = 'R ';
                156. P = BT-> biTree;
                157. P = p-> rchild;
                158. }
                159. } // While
                160. }
                161. // Hierarchical Traversal
                162. Void LevelOrder (BiTree T ){
                163. BiTree p = T;
                164. // Queue
                165. Queue Queue;
                166. // Enter the root node
                167. Queue. push (p );
                168. // The queue is not empty.
                169. While (! Queue. empty ()){
                170. // The opponent element leaves the queue
                171. P = queue. front ();
                172. // Access the node pointed to by p
                173. Printf ("% c", p-> data );
                174. // Exit the queue
                175. Queue. pop ();
                176. // Leave the left subtree empty.
                177. If (p-> lchild! = NULL ){
                178. Queue. push (p-> lchild );
                179. }
                180. // Enter the right subtree if it is not empty.
                181. If (p-> rchild! = NULL ){
                182. Queue. push (p-> rchild );
                183. }
                184. }
                185. }
                186. Int main ()
                187. {
                188. BiTree T;
                189. CreateBiTree (T );
                190. Printf ("sequential traversal: \ n ");
                191. PreOrder (T );
                192. Printf ("\ n ");
                193. Printf ("first-order traversal (non-recursive): \ n ");
                194. PreOrder2 (T );
                195. Printf ("\ n ");
                196. Printf ("sequential traversal: \ n ");
                197. InOrder (T );
                198. Printf ("\ n ");
                199. Printf ("sequential traversal (non-recursive): \ n ");
                200. InOrder2 (T );
                201. Printf ("\ n ");
                202. Printf ("sequential traversal: \ n ");
                203. PostOrder (T );
                204. Printf ("\ n ");
                205. Printf ("post-order traversal (non-recursive): \ n ");
                206. PostOrder2 (T );
                207. Printf ("\ n ");
                208. Printf ("hierarchical traversal: \ n ");
                209. LevelOrder (T );
                210. Printf ("\ n ");
                211. Return 0;
                212. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.