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:
class TreeNode:def __init__(self, val, left=None, right=None):self.val = valself.left = leftself.right = rightdef 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 nodepathSum = 10 * pathSum + currentNode.val# if the current node is a leaf, return the current path sumif currentNode.left is None and currentNode.right is None:return pathSum# traverse the left and the right sub-treereturn 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
anddisplay_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.
tab = 0# Display List Code Below:def height(node):if (node == None):return 0return 1 + max(height(node.left), height(node.right))def draw_node(output, link_above, node, level, p, link_char):if (node == None):returnout = "["h = len(output)SP = " "if (p < 0):for s in output:if (s):s = " "*(-1*p) + sfor s in link_above:if (s):s = " "*(-1*p) + sif 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 leftif (node.left):leftData = SP + str(node.left.val) + SPdraw_node(output, link_above, node.left,level + 1, p - len(leftData), 'L')p = max(p, len(output[level + 1]))# Enter this dataspace = p - len(output[level])if (space > 0):output[level] += (' ' * space)node_data = SP + str(node.val) + SPoutput[level] += node_data# Add vertical link abovespace = p + len(SP) - len(link_above[level])if (space > 0):link_above[level] += (' ' * space)link_above[level] += link_char# Fill in to rightif (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 linesfor 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 = jif (link_above[i][j] == 'L'):while (output[i - 1][jj] == ' '):jj += 1for 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-1for k in range(j-1, jj+1, -1):temp = output[i - 1]list1 = list(temp)list1[k] = '_'output[i - 1] = ''.join(list1)k = k - 1str1 = link_above[i]list1 = list(str1)list1[j] = '|'link_above[i] = ''.join(list1)# Outputfor 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 = valself.left = leftself.right = rightdef 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 tabtab += 1if 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 nodeprint(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.valprint("")# if the current node is a leaf, return the current path sumif 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-treeprint(tab*"\t" + "Recursive call to the left subtree of node ", currentNode.val)x = find_root_to_leaf_path_numbers(currentNode.left, pathSum)tab -=1print(tab*"\t" + "Recursive call to the right subtree of node ", currentNode.val)y = find_root_to_leaf_path_numbers(currentNode.right, pathSum)tab -=1print(tab*"\t" + "Adding pathSum from the left and right subtree: ", x, " + ", y, " = ", x+y, sep = "")print("")return x + ydef 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 tabtab = 0main()