Search code examples
javaalgorithmpreorder

Preorder Binary Tree Traversal


I need help in Preorder Binary Tree Traversal I understand how it travels (root, left, right) but look at that example (a)

enter image description here Why did they write it this way? According to the rule, we should go to *, but it went to 2 Is it because 2 have no children?


Solution

  • Preorder binary tree traversal algorithm:

    1. Visit the root.
    2. Traverse the left subtree, i.e., call Preorder(left-subtree)
    3. Traverse the right subtree, i.e., call Preorder(right-subtree);

    Thus, first you traverse the root + then go to step 2 and visit the left subtree -, and then the traversal algorithm is called again from - root and the algorithm takes the first its step, but now its root is -. After the first step algorithm go to step 2, and its left subtree is 2, and e.t.c.

    So, for you better understanding you might look this video Tree Traversals