...

/

Sum of Path Numbers (medium)

Sum of Path Numbers (medium)

Dry-run template

The following is the implementation of the solution provided for the problem posed in the Sum of Path Numbers (medium) lesson:

Press + to interact
Python 3.5
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_sum_of_path_numbers(root):
return find_root_to_leaf_path_numbers(root, 0)
def find_root_to_leaf_path_numbers(currentNode, pathSum):
if currentNode is None:
return 0
# calculate the path number of the current node
pathSum = 10 * pathSum + currentNode.val
# if the current node is a leaf, return the current path sum
if currentNode.left is None and currentNode.right is None:
return pathSum
# traverse the left and the right sub-tree
return find_root_to_leaf_path_numbers(currentNode.left, pathSum) + find_root_to_leaf_path_numbers(currentNode.right, pathSum)
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
print("Total Sum of Path Numbers: " + str(find_sum_of_path_numbers(root)))
main()

Sample input #1

root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)

	      _ 1 _ 
	     |     |
	   _ 0   _ 1 _ 
	  |     |     |
	  1     6     5 

The Total sum column is equal to the sum of numbers returned by the left and the right sub-trees.

Line number

root

Recursive call

currentNode

Pathsum

Total sum

9

1

-

-

0

-

13-21

1

-

1

1

-

24

1

Left subtree

0

10

-

24

0

Left subtree

1

101

-

24

0

Right subtree

None

0

101 + 0 = 110

24

1

Right subtree

1

11

-

24

1

Left subtree

6

116

-

24

1

Right subtree

5

115

116 + 115 = 231

34

-

-

-

-

101 + 231 = 332

Sample input #2

root = TreeNode(2)
root.left = TreeNode(0)
root.right = TreeNode(3)
root.left.left = TreeNode(1)
root.right.left = TreeNode(4)

	      _ 2 _ 
	     |     |
	   _ 0   _ 3 
	  |     |
	  1     4 

Students may be encouraged to complete the dry-run with this input:

Line number

root

Recursive call

currentNode

Pathsum

Total sum

9

2

-

-

0

-

13-21

2

-

2

2

-

24

2

Left subtree

0

20

-

24

0

Left subtree

1

201

-

...

...

...

...

...

...

Trace generation

The output of the following code shows the traces generated via print statements.

Note: draw_node and display_tree methods aid in visualizing the tree structure. The students can be encouraged to write these methods themselves. They don’t affect the code execution.

Press + to interact
Python 3.5
tab = 0
# Display List Code Below:
def height(node):
if (node == None):
return 0
return 1 + max(height(node.left), height(node.right))
def draw_node(output, link_above, node, level, p, link_char):
if (node == None):
return
out = "["
h = len(output)
SP = " "
if (p < 0):
for s in output:
if (s):
s = " "*(-1*p) + s
for s in link_above:
if (s):
s = " "*(-1*p) + s
if level < h - 1:
p = max(p, len(output[level + 1]))
if (level > 0):
p = max(p, len(output[level - 1]))
p = max(p, len(output[level]))
# Fill in to left
if (node.left):
leftData = SP + str(node.left.val) + SP
draw_node(output, link_above, node.left,
level + 1, p - len(leftData), 'L')
p = max(p, len(output[level + 1]))
# Enter this data
space = p - len(output[level])
if (space > 0):
output[level] += (' ' * space)
node_data = SP + str(node.val) + SP
output[level] += node_data
# Add vertical link above
space = p + len(SP) - len(link_above[level])
if (space > 0):
link_above[level] += (' ' * space)
link_above[level] += link_char
# Fill in to right
if (node.right):
draw_node(output, link_above, node.right,
level + 1, len(output[level]), 'R')
def display_tree(root):
if (root == None):
print("\tNone")
h = height(root)
output = []
link_above = []
for i in range(0, h):
output.append("")
link_above.append("")
draw_node(output, link_above, root, 0, 5, ' ')
# Create link lines
for i in range(h):
for j in range(len(link_above[i])):
if (link_above[i][j] != ' '):
size = len(output[i - 1])
if (size < j + 1):
output[i - 1] += " " * (j + 1 - size)
jj = j
if (link_above[i][j] == 'L'):
while (output[i - 1][jj] == ' '):
jj += 1
for k in range(j+1, jj-1):
str1 = output[i - 1]
list1 = list(str1)
list1[k] = '_'
output[i - 1] = ''.join(list1)
elif(link_above[i][j] == 'R'):
while (output[i - 1][jj] == ' '):
jj -= 1
# k = j-1
for k in range(j-1, jj+1, -1):
temp = output[i - 1]
list1 = list(temp)
list1[k] = '_'
output[i - 1] = ''.join(list1)
k = k - 1
str1 = link_above[i]
list1 = list(str1)
list1[j] = '|'
link_above[i] = ''.join(list1)
# Output
for i in range(h):
if (i):
print("\t", link_above[i])
print("\t", output[i])
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_sum_of_path_numbers(root):
return find_root_to_leaf_path_numbers(root, 0)
def find_root_to_leaf_path_numbers(currentNode, pathSum):
global tab
tab += 1
if currentNode is None:
print(tab*"\t" + "Current node: None")
print(tab*"\t" + "Returning pathSum = 0")
print("")
return 0
# calculate the path number of the current node
print(tab*"\t" + "Current node value: ", currentNode.val, sep="")
print(tab*"\t" + "pathSum = 10 * ", pathSum, " + ", currentNode.val, " = ",10 * pathSum + currentNode.val, sep="")
pathSum = 10 * pathSum + currentNode.val
print("")
# if the current node is a leaf, return the current path sum
if currentNode.left is None and currentNode.right is None:
print(tab*"\t" + "At the leaf node --> returning pathSum: ", pathSum, sep="")
print("")
return pathSum
# traverse the left and the right sub-tree
print(tab*"\t" + "Recursive call to the left subtree of node ", currentNode.val)
x = find_root_to_leaf_path_numbers(currentNode.left, pathSum)
tab -=1
print(tab*"\t" + "Recursive call to the right subtree of node ", currentNode.val)
y = find_root_to_leaf_path_numbers(currentNode.right, pathSum)
tab -=1
print(tab*"\t" + "Adding pathSum from the left and right subtree: ", x, " + ", y, " = ", x+y, sep = "")
print("")
return x + y
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
root2 = TreeNode(10)
root2.left = TreeNode(3)
root2.right = TreeNode(4)
root2.right.left = TreeNode(1)
input = [root, root2]
for i in input:
print("Input tree:")
display_tree(i)
print("Total Sum of Path Numbers: " +
str(find_sum_of_path_numbers(root)))
print(("-"*100)+"\n")
global tab
tab = 0
main()