返回

LeetCode 112:在二叉树中添加一行**

前端

探索二叉树奥秘:在特定深度处添加一行节点

在计算机科学中,二叉树是一种非线性数据结构,其中每个节点至多有两个子节点。它们在解决各种问题中发挥着至关重要的作用,从文件系统管理到人工智能。

LeetCode 112 题考查了你在二叉树中操纵节点的能力。题目要求你在给定深度处添加一个值为 val 的节点行。理解如何有效地修改二叉树的结构对于解决这一问题至关重要。

深度优先搜索:递归的解决方案

深度优先搜索 (DFS) 是一种遍历树形结构的算法,它通过深度优先地探索每个子树来工作。对于此问题,我们可以使用 DFS 在二叉树中递归地查找给定的深度。

def addOneRow(root, val, depth):
    if not root:
        return TreeNode(val)
    if depth == 1:
        return TreeNode(val, root)
    root.left = addOneRow(root.left, val, depth-1)
    root.right = addOneRow(root.right, val, depth-1)
    return root

广度优先搜索:层级遍历

广度优先搜索 (BFS) 是一种遍历树形结构的算法,它通过逐层遍历所有节点来工作。对于此问题,我们可以使用 BFS 在二叉树中迭代地查找给定的深度。

def addOneRow(root, val, depth):
    if not root:
        return TreeNode(val)
    if depth == 1:
        return TreeNode(val, root)
    queue = [root]
    while queue and depth > 1:
        depth -= 1
        level_size = len(queue)
        for i in range(level_size):
            node = queue.pop(0)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
            if depth == 1:
                node.left = TreeNode(val)
                node.right = TreeNode(val)
    return root

总结:深思熟虑,巧妙修改

LeetCode 112 题要求我们修改二叉树的结构。通过使用深度优先搜索或广度优先搜索算法,我们可以有效地在给定深度处添加一个值为 val 的节点行。理解树形结构的基本原理和遍历算法对于解决此类问题至关重要。