Sub topic 3
Parents, Children, and Siblings
This chapter assumes you can read basic Python, follow recursion, and know that objects can hold references to other objects. You already know a tree is made of nodes joined by edges, and that one node is the root. Here we name the relationships between neighboring nodes.
The three family terms
Every edge in a tree connects two nodes, one above the other. The words below describe that pair.
- Parent: the node directly above another node, one edge closer to the root.
- Child: a node directly below another node, one edge farther from the root.
- Siblings: nodes that share the same parent.
Every node except the root has exactly one parent. The root has none. A node can have any number of children, including zero.
In the diagram, A is the parent of B, C, and D. Those three are siblings. E and F are children of B, so they are siblings of each other. E and C are not siblings, because their parents differ (B and A).
Finding these relationships in code
The Node class from earlier stores children directly, so finding children is easy. Finding a parent is not, because the node has no link upward. One way is to search from the root.
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children or []
def find_parent(root, target):
for child in root.children:
if child is target:
return root
found = find_parent(child, target)
if found is not None:
return found
return None
def siblings(root, target):
parent = find_parent(root, target)
if parent is None:
return [] # the root, or a node not in this tree
return [c for c in parent.children if c is not target]
e, f, c = Node("E"), Node("F"), Node("C")
b = Node("B", [e, f])
d = Node("D", [Node("G")])
tree = Node("A", [b, c, d])
print(find_parent(tree, e).value) # B
print([n.value for n in siblings(tree, e)]) # ['F']
print(find_parent(tree, tree)) # NoneThe root returns None from find_parent because nothing is above it. The siblings function returns an empty list for it, since a node with no parent has no siblings.
Common errors
- Calling any lower node a "child." A child is exactly one edge below. G is a child of D, but only a descendant of A. The next chapters cover descendants.
- Treating cousins as siblings. Siblings need the same parent, not just the same depth.
- Assuming nodes know their parent. In this
Nodeclass they do not. Searching for a parent costs time proportional to the tree size. Many implementations add aparentfield if they need it often.
Exercise
In the tree above, which nodes are siblings of B, and which node is the parent of G?
Show answer
The siblings of B are C and D, because all three have parent A. The parent of G is D.