内容中心

2026年比较好的PE海绵主流厂家对比评测-上海莫源实业有限公司

To solve the problem of finding the sum of all elements in a binary tree, we need to use a recursive approach that accounts for null nodes (base case) and accumulates the sum of the current node's value plus the sums of its left and right subtrees.

Common Mistake in Original Code

The original code likely missing the base case for null nodes. Without checking if a node is null, accessing node.data on a null reference will cause an error.

Correct Solution Code

Assuming the tree node is defined with data, left, and right attributes:

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def sum_of_tree(root):
    # Base case: if node is null, contribute 0 to the sum
    if root is None:
        return 0
    # Recursive case: sum current node + left subtree + right subtree
    return root.data + sum_of_tree(root.left) + sum_of_tree(root.right)

Explanation

  1. Base Case: When the node is None (no child), return 0—this stops the recursion and avoids null reference errors.
  2. Recursive Case: For a non-null node, add its value to the sum of its left subtree and right subtree.

This approach efficiently traverses all nodes (each node is visited once) with a time complexity of O(n) (n = number of nodes) and space complexity of O(h) (h = height of the tree, due to recursion stack).

Answer: The correct code includes the base case for null nodes, as shown above. The key fix is adding if root is None: return 0. The final sum is computed by recursively summing the current node and its subtrees.

上海莫源实业有限公司

上海莫源实业有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?