LeetCode 623 在二叉树中增加一行 Python
2018-09-29 21:41
344 查看
给定一个二叉树,根节点为第1层,深度为 1。在其第
d层追加一行值为
v的节点。
添加规则:给定一个深度值
d(正整数),针对深度为
d-1层的每一非空节点
N,为
N创建两个值为
v的左子树和右子树。
将
N原先的左子树,连接为新节点
v的左子树;将
N原先的右子树,连接为新节点
v的右子树。
如果
d的值为 1,深度 d - 1 不存在,则创建一个新的根节点
v,原先的整棵树将作为
v的左子树。
示例 1:
输入: 二叉树如下所示: 4 / \ 2 6 / \ / 3 1 5 v = 1 d = 2 输出: 4 / \ 1 1 / \ 2 6 / \ / 3 1 5
示例 2:
输入: 二叉树如下所示: 4 / 2 / \ 3 1 v = 1 d = 3 输出: 4 / 2 / \ 1 1 / \ 3 1
注意:
- 输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。
- 输入的二叉树至少有一个节点
[code]class Solution: def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ if d == 1: tmp = TreeNode(v) tmp.left = root return tmp #讨论d>1的情形 queue = [(root,1)] #首先要将所有d-1层的节点都加进来 while queue: item = queue.pop(0) (TmpNode,depth) = item if depth >= d-1: queue.insert(0,(TmpNode,depth)) break if TmpNode.left: queue.append((TmpNode.left,depth+1)) if TmpNode.right: queue.append((TmpNode.right,depth+1)) #此时所有depth=d-1的节点都放进了queue for (node,depth) in queue: tmp = node.left mynode = TreeNode(v) node.left = mynode mynode.left = tmp tmp = node.right mynode = TreeNode(v) node.right = mynode mynode.right = tmp return root
相关文章推荐
- [LeetCode] Add One Row to Tree 二叉树中增加一行
- python 矩阵增加一行或一列
- LeetCode 105,106. Construct Binary Tree 重建二叉树 Python Solution
- LeetCode--Invert Binary Tree (反转二叉树)Python
- 每天一道LeetCode-----为二叉树增加next节点,指向同一层的下一个节点
- LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python
- python 矩阵增加一行或一列的实例
- LeetCode--102. Binary Tree Level Order Traversal(二叉树水平遍历)Python
- leetcode | 按层访问一棵二叉树 | Python
- LeetCode--Merge Two Binary Trees(合并两个二叉树)Python
- LeetCode 331. Verify Preorder Serialization of a Binary Treet 二叉树前序遍历验证 Python Solution
- leetcode 计算二叉树中出现最多的元素,Python实现
- [leetcode]Path Sum II @ Python
- 47. Permutation II Leetcode Python
- [LeetCode] 038. Count and Say (Easy) (C++/Python)
- [Leetcode,python] Hamming Distance 汉明距离
- [LeetCode]题解(python):049-Group Anagrams
- 【leetCode】Binary Tree Level Order Traversal python实现
- python- leetcode - Two Sum