LeetCode知识点总结 - 623

该博客介绍了如何使用BFS(广度优先搜索)算法解决LeetCode题目的623号问题,即在二叉树中添加指定深度的新节点。通过递归和层次遍历,实现给定根节点和值、深度参数的树结构扩展。适合DFSMedium难度的面试准备。

LeetCode 623. Add One Row to Tree

考点难度
DFSMedium
题目

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值