I am not understanding how to trace Binary Tree Traversals. Could someone explai
ID: 3620458 • Letter: I
Question
I am not understanding how to trace Binary Tree Traversals. Could someone explain to me inorder, preorder, and postorder traversals in a more efficient way?For example:
Reconstruct the exact BINARY tree given the following traversals:
Inorder: 9, 2, 10, 6, 5, 8, 3, 1, 4, 7
Post order: 9, 10, 2, 6, 8, 3, 7, 4, 1, 5
Any help is much appreciated!
Explanation / Answer
Dear.. Traversing a tree means visiting all the nodes of a tree in order. There are three different methods of traversing a binary tree: pre-order traversal in-order traversal post-order traversal in the pre-order, the root is visited before (pre) the subtrees traversals Procedure: 1. Start at the root node 2. Traverse the left subtree 3. Traverse the right subtree Code: void preOrder(Tree *tree) { if (tree->isEmpty( )) return; visit(tree->getRoot( )); preOrder(tree->getLeftSubtree()); preOrder(tree->getRightSubtree()); } EX: 9, 2, 10, 6, 5, 8, 3, 1, 4, 7 inOrder: In Inorder, the root is visited in-between left and right subtree traversal Inorder Traversal Procedure: 1. Traverse left subtree 2. Visit the root 3.Traverse right subtree Code: void preOrder(Tree *tree) { if (tree->isEmpty( )) return; visit(tree->getRoot( )); preOrder(tree->getLeftSubtree()); preOrder(tree->getRightSubtree()); } EX: 1,2,3,4,5,6,7,8,9,10. Post order: In the post order the root is visited after the subtrees traversals Procedure: 1. Traverse left subtree 2. Traverse right subtree 3. Visit the root Code: void postOrder(Tree *tree) { if (tree->isEmpty( )) return; postOrder(tree->getLeftSubtree( )); postOrder(tree->getRightSubtree( )); visit(tree->getRoot( )); } EX: 9, 10, 2, 6, 8, 3, 7, 4, 1, 5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.