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

如何在本地VSCode中调试LeetCode 199题二叉树右视图代码

在VS Code中本地调试LeetCode 199题代码指南

完全可以在VS Code里本地调试你的代码,先解决几个关键问题,再按步骤操作:

一、代码的核心问题

你调用rightSideView([1,2,3,None,5,None,4])时传入的是数组,但函数要求的是TreeNode类型的根节点,必须先把数组转换成二叉树结构才能正常运行。另外原代码的BFS逻辑存在错误,无法正确获取右视图节点。

二、修正后的可运行代码

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

def array_to_tree(arr):
    if not arr:
        return None
    root = TreeNode(arr[0])
    queue = [root]
    i = 1
    while queue and i < len(arr):
        node = queue.pop(0)
        if arr[i] is not None:
            node.left = TreeNode(arr[i])
            queue.append(node.left)
        i += 1
        if i < len(arr) and arr[i] is not None:
            node.right = TreeNode(arr[i])
            queue.append(node.right)
        i += 1
    return root

def rightSideView(root):
    res = []
    if not root:
        return res
    queue = [root]
    
    while queue:
        level_size = len(queue)
        for n in range(level_size):
            current_node = queue.pop(0)
            # 取当前层最后一个节点,就是右侧能看到的节点
            if n == level_size - 1:
                res.append(current_node.val)
            # 按左到右顺序入队,保证层序遍历的正确性
            if current_node.left:
                queue.append(current_node.left)
            if current_node.right:
                queue.append(current_node.right)
    return res

# 先将数组转成二叉树结构再调用函数
root = array_to_tree([1,2,3,None,5,None,4])
print(rightSideView(root))

三、VS Code调试步骤

  1. 安装Python插件:打开VS Code,在扩展市场搜索"Python"安装官方插件。
  2. 生成调试配置:按F5键,选择"Python"环境,VS Code会自动在项目目录下生成.vscode/launch.json配置文件,直接使用默认配置即可。
  3. 设置断点:在代码中需要查看逻辑的行左侧点击(比如res.append(current_node.val)、current_node = queue.pop(0)这些行),出现红色圆点即为断点。
  4. 启动调试:再次按F5,程序会停在第一个断点处。
  5. 调试操作:
    • F10:单步跳过,执行当前行并跳到下一行,不进入函数内部。
    • F11:单步进入,进入当前行调用的函数内部(比如进入array_to_tree查看树的构建过程)。
    • Shift+F11:单步跳出,从当前函数返回上一层。
    • 查看变量:在左侧"运行和调试"面板的"变量"栏,可实时查看queue、res、current_node等变量的当前值,理清每一步运行逻辑。

内容的提问来源于stack exchange,提问作者Joelinton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:10:36