Binary tree traversal: Preorder, Inorder, Post-order, BFS, DFS, Level Order, zig zag order

In order to illustrate the 3 traversals - pre order, in-order and post-order lets take following tree: Preorder traversal: To traverse a binary tree in Preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the left subtree, and (iii) 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 Implementing pre-order traversal [Read More]

Construct a full binary tree from a pre-order list of marked nodes

Question: construct a full binary tree from a list of nodes in pre-order. The nodes are marked ‘i’ if they are inner nodes and are marked ‘l’ if they are leaf nodes. Example given a list of nodes marked as (i, i, i, l, l, i, l, l, i, l, l), we need to construct a tree from those nodes so that the result looks like this: Notice how all “l” nodes are leaf nodes and “i” nodes are inner nodes? [Read More]

Construct a tree given its inorder and preorder traversal strings. Similarly construct a tree given its inorder and post order traversal strings.

For Inorder And Preorder traversals inorder = g d h b e i a f j c preorder = a b d g h e i c f j Scan the preorder left to right using the inorder sequence to separate left and right subtrees. For example, “a” is the root of the tree; “gdhbei” are in the left subtree; “fjc” are in the right subtree. “b” is the next root; “gdh” are in the left subtree; “ei” are in the right subtree. [Read More]

Pre Order traversal - Recursive and Iterative solution

Example Consider the tree: div class="separator” style="clear: both; text-align: center;“> To traverse a binary tree in Preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the left subtree, and (iii) 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 Recursive solution preorder(N \*root) { if(root) { printf("Value : %d", root->value); preorder(root->left); preorder(root->right); } } Iterative solution [Read More]