(License: CC BY-SA 4.0)
Prev - Errors and Exceptions, Next - Data structures and performance
What is the advantage over loops?
Limitations?
$$f(n)=n!$$ $$f(n)=n\times{}(n-1)\times\cdots\times{}2\times{}1$$
What is the repeating part versus the termination condition?
For demo purposes only, not today’s class activity.
A binary tree :
Always true in sorted binary tree (or binary search tree - BST) : $a<b<c$
Not a linear data structure, b
is root node, b.left=a
and b.right=c
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
Can we write a non-recursive program to count all the nodes in tree?
Start with root
node object (root.info=4
), and you can go root.left
or root.right
to get to the next node. If there is no node, it will be an empty object (None
).
Does it work for any tree?
def node_count(node, count):
if node.left:
count = node_count(node.left, count + 1)
if node.right:
count = node_count(node.right, count + 1)
return count
print(node_count(root, 1))
Does it work for any tree?
Advanced:
Post your solution link on Piazza.