
Code
Walking the Tree
A binary tree is made of nodes where each node has up to two
children: left and right. The top node is the root; nodes
with no children are leaves.
B
/ \
A D
/ \
C E
Trees are recursive: every child is the root of a smaller tree.
So tree code is usually recursive too, with None as the base case.
Three ways to walk
- Preorder: node, then left, then right gives
B A D C E - Inorder: left, then node, then right gives
A B C D E - Postorder: left, then right, then node gives
A C E D B
def count(node):
if node is None:
return 0
return 1 + count(node.left) + count(node.right)
Height
The height is the number of nodes on the longest path from the root down to a leaf. An empty tree has height 0, a single node 1.
Assignment
preorder(node)returns a list of values in preorder.inorder(node)returns a list of values in inorder.height(node)returns the tree's height (Nonehas height 0).
preorder(node)returns a list of values in preorder.inorder(node)returns a list of values in inorder.height(node)returns the tree's height (Nonehas height 0).
main.py Python sleeping
Press Run to try your code, then Check to test it.