LeetCode 623. Add One Row to Tree
| 考点 | 难度 |
|---|---|
| DFS | Medium |
题目
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur’s left subtree root and right subtree root.
cur’s original left subtree should be the left subtree of the new left subtree root.
cur’s original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root’s left subtree.
思路
BFS 并且记录层数
答案
class Solution(object):
def addOneRow(self, root, v, d):
if d == 1:
return TreeNode(v, root, None)
bfs = deque([root])
while bfs and d != 1:
size = len(bfs)
d -= 1
for _ in range(size):
curr = bfs.popleft()
if curr.left != None:
bfs.append(curr.left)
if curr.right != None:
bfs.append(curr.right)
if d == 1: # Current level is in depth d-1 -> Add nodes with value `v`
curr.left = TreeNode(v, curr.left, None)
curr.right = TreeNode(v, None, curr.right)
return root
该博客介绍了如何使用BFS(广度优先搜索)算法解决LeetCode题目的623号问题,即在二叉树中添加指定深度的新节点。通过递归和层次遍历,实现给定根节点和值、深度参数的树结构扩展。适合DFSMedium难度的面试准备。

8870

被折叠的 条评论
为什么被折叠?



