Algorithms Flashcards
1
Q
What are the different ways to traverse a binary tree?
A
- Preorder
- In order
- Postorder
2
Q
How do all of the tree traversal algorithms work?
A
- Algorithm given a input
- Algorithm outputs a data in a different order
- Depending on algorithm used
3
Q
How does preorder traversal work?
A
- The top down traversal method
- Encounters all roots before encountering the leaves
- Left over right
4
Q
What is the pseudo code for preorder traversal?
A
5
Q
How does in order traversal work?
A
- Traverse left sub tree
- Visit the root first
- Traverse the right sub tree
6
Q
What is the pseudo code for in order traversal?
A
7
Q
How does post order traversal work?
A
- Bottom up traversal
- Encounter all the leaves before the roots
1. Traverse the left sub-tree
2, Traverse the right sub-tree
3. Visit the root
8
Q
What is the pseudo code for post order traversal?
A
9
Q
What is the infix notation?
A
- A + B
- The + notation is fixed in between the two operands (numbers)
10
Q
What is the problem with infix notation?
A
- When not using brackets with longer expressions
- Order of calculations can be ambiguous
- 2 * A + B
- Computers don’t know what to do first without brackets
11
Q
What is Polish notation?
A
- Alternative to infix notation
- A + B -> +A B
- Add number A to number B
- Prefix notation due to operator before opperand
- No ambiguity meaning its easier for computers to understand
12
Q
What is reverse Polish notation?
A
- Postfix notation
- Operator after operand
- A + B -> A B +
- No ambiguity
13
Q
Why is reverse Polish notation important in comp Sci?
A
- Unambiguous and doesn’t require brackets
- Can be worked out using stacks
14
Q
What can you do with infix notation (3*(1+2)) and a binary tree
A
- You can use reverse Polish notation to store tree traversal routes
15
Q
How do use a stack with reverse Polish notation
A
- You use the reverse Polish notation and go from left to right
- To push items onto stacks if they are numbers
- To pop items out of stacks and carry out calculations if there is an operator