Download presentation
Presentation is loading. Please wait.
1
Printing a search tree in order
When is root printed? After left subtree, before right subtree. void Visit(Node * t) { if (t != 0) Visit(t->left); cout << t->info << endl; Visit(t->right); } Inorder traversal “llama” “tiger” “monkey” “jaguar” “elephant” “giraffe” “pig” “hippo” “leopard”
2
Tree traversals Different traversals useful in different contexts
Inorder prints search tree in order Visit left-subtree, process root, visit right-subtree Preorder useful for reading/writing trees Process root, visit left-subtree, visit right-subtree Postorder useful for destroying trees Visit left-subtree, visit right-subtree, process root “llama” “tiger” “monkey” “jaguar” “elephant” “giraffe”
3
Printing a tree in pre order
When is root printed? before left subtree, before right subtree. void PreVisit(Node * t) { if (t != 0) cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); } preorder traversal “llama” “tiger” “monkey” “jaguar” “elephant” “giraffe” “pig” “hippo” “leopard”
4
How high is stack of calls (non-null t)?
void PreVisit(Node * t) { if (t != 0) { cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); } void PreVisit(Node * t) { if (t != 0) { cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); } void PreVisit(Node * t) { if (t != 0) { cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); } void PreVisit(Node * t) { if (t != 0) { cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); } PreVisit(root) “jaguar” “elephant” “giraffe” “hippo” “leopard” void PreVisit(Node * t) { if (t != 0) { cout << t->info << endl; PreVisit(t->left); PreVisit(t->right); }
5
Printing a tree in post order
When is root printed? after left subtree, after right subtree. void PostVisit(Node * t) { if (t != 0) PostVisit(t->left); PostVisit(t->right); cout << t->info << endl; } preorder traversal “llama” “tiger” “monkey” “jaguar” “elephant” “giraffe” “pig” “hippo” “leopard”
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.