Binary trees Flashcards
Preorder reversal - code and traversal order?
Preorder (D,L,R)
void Preorder(Node *root) { if (root == null) return; printf("%c ", root->data); Preorder(root->left); Preorder(root->right); }
In-order reversal - code and traversal order?
In-order (L,D,R)
void Inorder(Node *root) { if (root == null) return; Preorder(root->left); printf("%c ", root->data); Preorder(root->right); }
Postorder (L,R,D) - code and traversal order?
Postorder (L,R,D)
void Postorder(Node *root) { if (root == null) return; Preorder(root->left); Preorder(root->right); printf("%c ", root->data); }
What’s the time and space complexity for depth-first traversal?
- Time complexity =
O(n)
for all cases - Space complexity =
O(h)
— height of the tree.
WorstO(n)
,
Best/averageO(log n)
What are the depth-first traversal algorithms?
- Preorder
- Inorder
- Postorder
What is the breadth-first traversal algorithm?
- Level-order
What’s the recipe for level order traversal?
LEVEL ORDER RECIPE (Queue (FIFO)):
- Create queue with root node as the first item in queue
- While queue NOT empty -> while loop
- Dequeue front element (current), add left & right to end of queue
#include void LevelOrder(Node *root) { if (root == null) return; queue Q; Q.push(root); while(!Q.empty()) { Node* current = Q.front(); if(current->left != null) Q.push(current->left); if(current->right != null) Q.push(current->right); Q.pop(); } }
What’s the time and space complexity of level order traversal?
Time complexity = O(n) — all cases irrespective of tree size
Space-complexity = O(1) — best, O(n) — worst/average
C++ syntax: how do you import queue?
include
C++ syntax: what’s q.empty() do?
Returns boolean true if queue has 0 items
C++ syntax: what’s q.pop() do?
Removes first/next item
C++ syntax: what’s q.front() do?
Returns first/next item of the queue without removing it.
How do you find the height of a tree recursively with code?
int FindHeight(struct Node *root) { if (root == NULL) return -1; return max( FindHeight(root->left), FindHeight(root->right) ) + 1; }
What are the 4 areas in memory allocation?
- Heap
- Stack
- Global/static
- Code (text)
What’s the difference between height count and depth count?
Depth count = the leaf nodes or bottom of the tree
Height = top of the tree or root node (e.g. height = 0 at the leaf nodes, height = 3 at root)