I am working on the problem of finding the minimum path sum in a binary tree, and printing the path. The path can be from the root node to any leaf node.
Here is my code in Python 2.7. I am looking for advice for bugs, performance improvement ideas or general code style advice.
One specific question is: I am using a list result
to track minimal sum so far, because a simple integer in Python 2.7 is not reference type (I mean change the value of an integer in one function call, does not impact the value of same variable in another function). Are there any more elegant ways to track the minimal sum so far?
class TreeNode:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def min_path(self, sum_so_far, prefix, result, result_path):
if self.left:
prefix.append(self.value)
self.left.min_path(sum_so_far + self.value, prefix, result, result_path)
prefix.pop(-1)
if self.right:
prefix.append(self.value)
self.right.min_path(sum_so_far + self.value, prefix, result, result_path)
prefix.pop(-1)
if not self.left and not self.right: # leaf node
prefix.append(self.value)
if sum_so_far + self.value < result[0]:
result[0] = sum_so_far + self.value
if len(result_path) > 0:
result_path.pop(0)
result_path.append(prefix[:])
prefix.pop(-1)
if __name__ == "__main__":
root = TreeNode(1, TreeNode(2, TreeNode(-4, None, None), TreeNode(5, None, None)), TreeNode(3, TreeNode(6, None, None), TreeNode(-7, None, None)))
result = [float('inf')]
result_path = []
root.min_path(0, [], result, result_path)
print result, result_path