Summary - Trees
- Algorithms course
- Intermediate
- Lesson 28/80
- 4 min
Walk a small binary tree and print its values in a mini task.
Summary - Trees
Tree: hierarchical, acyclic; n nodes, n-1 edges. Root, internal, leaf. Binary tree has at most 2 children.
Height: longest path; node count: 1 + left + right. Inorder/preorder/postorder traversals are O(n).
Trees underpin file systems, expression parsing and search (BST).
Practice Summary: inorder traversal
Write inorder(node). Left-root-right, print values. Print 1 2 3 with root = Node(2); root.left = Node(1); root.right = Node(3); inorder(root).
Starter code
def inorder(node):
# Left-root-right traversalSample solution
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(node):
# Left-root-right traversal
if node is None:
return
inorder(node.left)
print(node.val)
inorder(node.right)
root = Node(2)
root.left = Node(1)
root.right = Node(3)
inorder(root)Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Summary - Trees: match the terms
| Term | Meaning |
|---|---|
Root |
Topmost |
Leaf |
No children |
Height |
Longest path |
Inorder |
Left-root-right |
2 Node-edge
n nodes → ____ edges
n nodes → n - 1 edges
Explanation: n - 1 is right.
3 What does inorder give on a BST?
- Increasing order Correct answer
- Random
- Leaves
- Decreasing order
Explanation: Increasing order