You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在IntelliJ本地IDE中加载LeetCode格式的二叉树输入

如何将LeetCode层序遍历数组转换为TreeNode实例用于本地测试

你在本地IDE编写LeetCode二叉树算法题时,核心问题是:LeetCode的测试用例是层序遍历格式的数组(如[-10, 9, 20, None, None, 15, 7]),但本地直接传入数组无法适配TreeNode类型的参数要求。以下是具体解决方法:

1. 保留LeetCode的TreeNode定义

首先确保代码中包含LeetCode提供的TreeNode类定义,这是转换逻辑的基础:

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

2. 实现层序数组转TreeNode的工具函数

利用队列实现广度优先遍历,逐个创建节点并关联左右子节点,完全匹配LeetCode的数组转树逻辑:

from collections import deque

def array_to_tree(arr):
    if not arr:
        return None
    
    # 创建根节点
    root = TreeNode(arr[0])
    queue = deque([root])
    index = 1
    
    while queue and index < len(arr):
        current_node = queue.popleft()
        
        # 处理左子节点
        if arr[index] is not None:
            current_node.left = TreeNode(arr[index])
            queue.append(current_node.left)
        index += 1
        
        # 处理右子节点,避免索引越界
        if index < len(arr) and arr[index] is not None:
            current_node.right = TreeNode(arr[index])
            queue.append(current_node.right)
        index += 1
    
    return root

3. 修改测试代码,完成本地验证

用上述工具函数把LeetCode的数组测试用例转换成TreeNode实例,再传入你的Solution类方法即可测试:

class Solution(object):
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max_sum = float('-inf')
        
        def max_gain(node):
            if not node:
                return 0
            # 计算左右子树的有效贡献(负贡献则舍弃)
            left_gain = max(max_gain(node.left), 0)
            right_gain = max(max_gain(node.right), 0)
            # 更新全局最大路径和
            current_sum = node.val + left_gain + right_gain
            self.max_sum = max(self.max_sum, current_sum)
            # 返回当前节点的单路径最大贡献值
            return node.val + max(left_gain, right_gain)
        
        max_gain(root)
        return self.max_sum

# 测试流程
test_array = [-10, 9, 20, None, None, 15, 7]
root = array_to_tree(test_array)
print(Solution().maxPathSum(root))  # 预期输出:42

额外注意点

  • 你自己实现的BST类和LeetCode的TreeNode结构差异较大(BST包含depth属性,插入逻辑遵循二叉搜索树规则),无法直接适配题目要求,因此必须使用TreeNode类构建测试树。
  • 原解题代码中直接访问root.left.val会触发AttributeError(当节点的左/右子树为None时),上述示例已修正该问题,可参考调整自身代码逻辑。

内容的提问来源于stack exchange,提问作者Teoh Zhen Ying

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 12:37:44