- 2070 Bhadra · 3+4 marks
Binary tree traversals; preorder of BST
Short answer
Preorder visits root, left subtree, right subtree (NLR); inorder (LNR) gives sorted order for BST; postorder (LRN) visits children before root. For the BST built from 20,10,18,4,8,5,13,16,47,1,27, the preorder sequence is 20, 10, 4, 1, 8, 5, 18, 13, 16, 47, 27.
Explain different traversal methods for a binary tree. What will be the result of pre-order traversal for given binary search tree with nodes: 20, 10, 18, 4, 8, 5, 13, 16, 47, 1, and 27?
A traversal visits every node of a binary tree exactly once. The three depth-first methods differ in when the root is visited (L = left, R = right, N = node/root).
| Traversal | Order | Rule |
|---|---|---|
| Preorder | N L R | visit root, traverse left subtree, traverse right subtree |
| Inorder | L N R | traverse left subtree, visit root, traverse right subtree |
| Postorder | L R N | traverse left subtree, traverse right subtree, visit root |
void preorder(struct node *p) { if (p) { printf("%d ", p->info); preorder(p->left); preorder(p->right); } }
void inorder(struct node *p) { if (p) { inorder(p->left); printf("%d ", p->info); inorder(p->right); } }
void postorder(struct node *p) { if (p) { postorder(p->left); postorder(p->right); printf("%d ", p->info); } }
Level-order (breadth-first) traversal using a queue is a fourth method.
Example for tree A(B,C): preorder A B C, inorder B A C, postorder B C A.
Preorder of the given BST
Insert 20, 10, 18, 4, 8, 5, 13, 16, 47, 1, 27 in order:
20
├─L:10
│ ├─L:4
│ │ ├─L:1
│ │ └─R:8
│ │ └─L:5
│ └─R:18
│ └─L:13
│ └─R:16
└─R:47
└─L:27
Preorder (root, left, right):
20, 10, 4, 1, 8, 5, 18, 13, 16, 47, 27
(Inorder check: 1, 4, 5, 8, 10, 13, 16, 18, 20, 27, 47, which is sorted, so the tree is correct.)
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Preorder and postorder of a BST · Data Structure and Algorithm, chapter 6
- Draw binary tree from preorder and inorder · Data Structure and Algorithm, chapter 6
- Strictly binary tree has 2n-1 nodes · Data Structure and Algorithm, chapter 6
- BST properties and recursive search · Data Structure and Algorithm, chapter 6
- Expression tree and traversals · Data Structure and Algorithm, chapter 6
- B-tree of order 3 for 52, 46, 27, ... · Data Structure and Algorithm, chapter 6
- Subnet 10.10.10.0/24 for 5, 16, 23, 27 · Computer Networks and Security, chapter 4 · asked 2×
- De Morgan's theorem and (-47+27) by 2's complement · Digital Logic, chapter 2
- Bresenham: line (20,10) to (30,18) · Computer Graphics, chapter 2 · asked 4×
- Decision tree formulas; 20 servers, 10 E · Telecommunications, chapter 6