📅  最后修改于: 2023-12-03 15:42:16.536000             🧑  作者: Mango
This is a question from the GATE-CS-2007 exam. It tests your understanding of algorithms and data structures.
Given a binary tree, find the maximum sum path from a leaf to the root. For example, in the following tree, the maximum sum is 27 (3 + 6 + 9 + 0 – 1 + 10).
10
/ \
2 10
/ \ \
20 1 -25
\
3
We can solve this problem using a simple DFS (depth-first search) algorithm. The first step is to define a recursive function that returns the maximum sum path from a given node to the root.
def max_sum_path(node):
if not node:
return 0
left_sum = max_sum_path(node.left)
right_sum = max_sum_path(node.right)
return max(left_sum, right_sum) + node.data
The function takes a node as an argument and returns the maximum sum path from that node to the root. If the node is None (i.e., it is a leaf), the function returns 0. Otherwise, it recursively calls itself on the left and right children of the node and returns the maximum of the two sums plus the current node's data.
The next step is to traverse the entire tree and find the maximum sum path from any leaf to the root. We can achieve this by iterating through all the leaves of the tree and computing the maximum sum path from that leaf to the root.
def max_sum_path_from_leaves(root):
if not root:
return 0
max_path_sum = float("-inf")
stack = [(root, [])]
while stack:
node, path = stack.pop()
if not node.left and not node.right: # leaf node
cur_path_sum = max_sum_path(node)
if cur_path_sum > max_path_sum:
max_path_sum = cur_path_sum
if node.left:
stack.append((node.left, path + [node.data]))
if node.right:
stack.append((node.right, path + [node.data]))
return max_path_sum
The function takes the root of the tree as an argument and returns the maximum sum path from any leaf to the root. It initializes a stack with the root node and an empty path.
It then pops a node and its path from the stack, computes the maximum sum path from that node to the root, and checks if it is greater than the current maximum sum path.
If it is, it updates the current maximum sum path. If the current node is not a leaf, it pushes its left and right children onto the stack along with the current path.
Finally, it returns the maximum sum path from any leaf to the root.
In conclusion, we have seen how to find the maximum sum path from any leaf to the root of a binary tree using a simple DFS algorithm. The algorithm has a time complexity of O(N), where N is the number of nodes in the tree.