0% found this document useful (0 votes)
28 views46 pages

17 Trees

The document describes operations on tree data structures. It defines a Tree class and methods like count_leaves(), print_tree(), leaves(), count_paths(), double(), and prune() that perform various traversals and transformations on tree objects. Examples are provided to demonstrate how each method works on sample tree inputs.

Uploaded by

Alex s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views46 pages

17 Trees

The document describes operations on tree data structures. It defines a Tree class and methods like count_leaves(), print_tree(), leaves(), count_paths(), double(), and prune() that perform various traversals and transformations on tree objects. Examples are provided to demonstrate how each method works on sample tree inputs.

Uploaded by

Alex s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

1

2
3
4
4
5
6
7
8
9
t = Tree(3, [
Tree(1),
Tree(2, [
Tree(1),
Tree(1)
])
])
10
label
branches

is_leaf

t = Tree(3, [
Tree(1),
Tree(2, [
Tree(1),
Tree(1)
])
])

t.label
t.is_leaf()
t.branches[0].is_leaf()

11
label
branches

is_leaf

t = Tree(3, [
Tree(1),
Tree(2, [
Tree(1),
Tree(1)
])
])

t.label # 3
t.is_leaf()
t.branches[0].is_leaf()

11
label
branches

is_leaf

t = Tree(3, [
Tree(1),
Tree(2, [
Tree(1),
Tree(1)
])
])

t.label # 3
t.is_leaf() # False
t.branches[0].is_leaf()

11
label
branches

is_leaf

t = Tree(3, [
Tree(1),
Tree(2, [
Tree(1),
Tree(1)
])
])

t.label # 3
t.is_leaf() # False
t.branches[0].is_leaf() # True

11
t = Tree(3, [Tree(1), Tree(2, [Tree(1), Tree(1)])])

t.label # 3
t.is_leaf() # False
t.branches[0].is_leaf() # True

Tree

12
t = Tree(3, [Tree(1), Tree(2, [Tree(1), Tree(1)])])

t.label # 3
t.is_leaf() # False
t.branches[0].is_leaf() # True

Tree

class Tree:
def __init__(self, label, branches=[]):
self.label = label
self.branches = list(branches)

def is_leaf(self):
return not self.branches

12
class Tree:

def __init__(self, label, branches=[]):


self.label = label
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)

def is_leaf(self):
return not self.branches

def __repr__(self):
if self.branches:
branch_str = ', ' + repr(self.branches)
else:
branch_str = ''
return 'Tree({0}{1})'.format(self.label, branch_str)

def __str__(self):
return '\n'.join(self.indented())

def indented(self):
lines = []
for b in self.branches:
for line in b.indented():
lines.append(' ' + line)
return [str(self.label)] + lines

draw() Tree

13
14
15
def count_leaves(t):
"""Returns the number of leaf nodes in T."""
if

else:

16
def count_leaves(t):
"""Returns the number of leaf nodes in T."""
if t.is_leaf():

else:

16
def count_leaves(t):
"""Returns the number of leaf nodes in T."""
if t.is_leaf():
return 1
else:

16
def count_leaves(t):
"""Returns the number of leaf nodes in T."""
if t.is_leaf():
return 1
else:
leaves_under = 0
for b in t.branches:
leaves_under += count_leaves(b)
return leaves_under

16
sum()

sum([1, 1, 1, 1]) # 4

17
sum()

sum([1, 1, 1, 1]) # 4

def count_leaves(t):
"""Returns the number of leaf nodes in T."""
if t.is_leaf():
return 1
else:
branch_counts = [count_leaves(b) for b in t.branches]
return sum(branch_counts)

17
def print_tree(t, indent=0):
"""Prints the labels of T with depth-based indent.
>>> t = Tree(3, [Tree(1), Tree(2, [Tree(1), Tree(1)])])
>>> print(t)
3
1
2
1
1
"""

18
def print_tree(t, indent=0):
"""Prints the labels of T with depth-based indent.
>>> t = Tree(3, [Tree(1), Tree(2, [Tree(1), Tree(1)])])
>>> print(t)
3
1
2
1
1
"""
print(indent * " " + t.label)
for b in t.branches:
print_tree(b, indent + 2)

19
def leaves(t):
"""Return a list containing the leaf labels of T.
>>> t = Tree(20, [Tree(12, [Tree(9, [Tree(7), Tree(2)]), Tree(3)]),
>>> leaves(t)
[7, 2, 3, 4, 4]
"""

sum([ [1], [2, 3], [4] ], []) # [1, 2, 3, 4]


sum([ [1] ], []) # [1]
sum([ [[1]], [2] ], []) # [[1], 2]

20
def leaves(t):
"""Return a list containing the leaf labels of T.
>>> t = Tree(20, [Tree(12, [Tree(9, [Tree(7), Tree(2)]), Tree(3)]),
>>> leaves(t)
[7, 2, 3, 4, 4]
"""
if t.is_leaf():
return [t.label]
else:
leaf_labels = [leaves(b) for b in t.branches]
return sum(leaf_labels, [])

21
def count_paths(t, total):
"""Return the number of paths from the root to any node in T
for which the labels along the path sum to TOTAL.

>>> t = Tree(3, [Tree(-1), Tree(1, [Tree(2, [Tree(1)]), Tree(3)]), Tree(1, [Tree(-


>>> count_paths(t, 3)
2
>>> count_paths(t, 4)
2
>>> count_paths(t, 5)
0
>>> count_paths(t, 6)
1
>>> count_paths(t, 7)
2
"""

22
def count_paths(t, total):
"""Return the number of paths from the root to any node in T
for which the labels along the path sum to TOTAL.

>>> t = Tree(3, [Tree(-1), Tree(1, [Tree(2, [Tree(1)]), Tree(3)]), Tree(1, [Tree(-


>>> count_paths(t, 3)
2
>>> count_paths(t, 4)
2
>>> count_paths(t, 5)
0
>>> count_paths(t, 6)
1
>>> count_paths(t, 7)
2
"""
if t.label == total:
found = 1
else:
found = 0
return found + sum([count_paths(b, total - t.label) for b in t.branches])

23
24
def double(t):
"""Returns a tree identical to T, but with all labels
if

else:

25
def double(t):
"""Returns a tree identical to T, but with all labels
if t.is_leaf():

else:

25
def double(t):
"""Returns a tree identical to T, but with all labels
if t.is_leaf():
return Tree(t.label * 2)
else:

25
def double(t):
"""Returns a tree identical to T, but with all labels
if t.is_leaf():
return Tree(t.label * 2)
else:
return Tree(t.label * 2,
[double(b) for b in t.branches])

25
def double(t):
"""Returns the number of leaf nodes in T."""
return Tree(t.label * 2,
[double(b) for b in t.branches])

26
27
def double(t):
"""Doubles every label in T, mutating T.
>>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
>>> double(t)
>>> t
Tree(2, [Tree(6, [Tree(10)]), Tree(14)])
"""
t.label = t.label * 2
for b in t.branches:
double(b)
28
def prune(t, n):
"""Prune all sub-trees whose label is n.
>>> t = Tree(3, [Tree(1, [Tree(0), Tree(1)]), Tree(2, [Tree(1), Tre
>>> prune(t, 1)
>>> t
Tree(3, [Tree(2)])
"""
t.branches = [___ for b in t.branches if ___]
for b in t.branches:
prune(___, ___)

29
def prune(t, n):
"""Prune all sub-trees whose label is n.
>>> t = Tree(3, [Tree(1, [Tree(0), Tree(1)]), Tree(2, [Tree(1), Tre
>>> prune(t, 1)
>>> t
Tree(3, [Tree(2)])
"""
t.branches = [b for b in t.branches if b.label !=n]
for b in t.branches:
prune(b, n)

30

You might also like