题目描述:
https://leetcode.com/problems/add-one-row-to-tree/
题目大意:
在某一层插入一行节点
解题思路:
基于双端队列、广度优先搜索的二叉树层序遍历
python代码:
# 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
class Solution(object):
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
if d==1:
new_root = TreeNode(v)
new_root.left = root
return new_root
Q = deque()
Q.append((root,1))
while Q:
node,level = Q.popleft()
if level == d-1:
temp_left = node.left
temp_right = node.right
node.left = TreeNode(v)
node.left.left = temp_left
node.right = TreeNode(v)
node.right.right = temp_right
else:
if node.left:
Q.append((node.left,level+1))
if node.right:
Q.append((node.right,level+1))
return root