Saved Bookmarks
| 1. |
What are tree traversals? |
|
Answer» Tree traversal is the process of visiting all the nodes of a tree. Since the root (head) is the first node and all nodes are connected via edges (or links) we always start with that node. There are three ways which we use to traverse a tree − 1. Inorder Traversal:
void printInorderTraversal(Node root) { if (root == null) return; //first traverse to the left subtree printInorderTraversal(root.left); //then print the data of node System.out.print(root.data + " "); //then traverse to the right subtree printInorderTraversal(root.right); }
2. Preorder Traversal:
void printPreorderTraversal(Node root) { if (root == null) return; //first print the data of node System.out.print(root.data + " "); //then traverse to the left subtree printPreorderTraversal(root.left); //then traverse to the right subtree printPreorderTraversal(root.right); }
3. Postorder Traversal:
void printPostorderTraversal(Node root) { if (root == null) return; //first traverse to the left subtree printPostorderTraversal(root.left); //then traverse to the right subtree printPostorderTraversal(root.right); //then print the data of node System.out.print(root.data + " "); }
Consider the following tree as an example, then:
|
|