Monday, February 10, 2014

Binary tree traversal: Preorder, Inorder, and Postorder

We take this picture as an example to illustrate the binary tree traversal

1

First, Pre-order Traversal:
(1) Visit the root;
(2) Traverse the left subtree;
(3) Traverse the right subtree.
Therefore, the Preorder traversal of the above tree will outputs:
7, 1, 0, 3, 2, 5, 4, 6, 9, 8, 10
Code in java:
public void preOrder(Node root) {
    if (node == null) {
        return null;
    }
    System.out.println(root.data);
    preOrder(root.left);
    preOrder(root.right);
}
Second, In-Order Traversal:
(1) Traverse the left most subtree starting at the left external node;
(2) Visit the root;
(3) Traverse the right subtree starting at the left external node.
Therefore, the Inorder traversal of the above tree will outputs:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Code in java:
public void inOrder(Node root) {
    if (node == null) {
        return null;
    }
    inOrder(root.left);
    System.out.println(root.data);
    inOrder(root.right);
}
Third, Post-Order Traversal:
(1) Traverse all the left external nodes
(2) Traverse the right subtree starting at the end left external node from (1)
(3) Visit the root
Therefore, the Postorder traversal of the above tree will outputs:
0, 2, 4, 6, 5, 3, 1, 8, 10, 9, 7
Code in java:
public void postOrder(Node root) {
    if (node == null) {
        return null;
    }
    postOrder(root.left);
    postOrder(root.right);
    System.out.println(root.data);
}

No comments:

Post a Comment