上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int val, int depth) {
}
};
python3 解法, 执行用时: 48 ms, 内存消耗: 16.6 MB, 提交时间: 2022-08-05 10:18:50
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode:
if depth == 1:
return TreeNode(val, root, None)
curLevel = [root]
for _ in range(1, depth - 1):
tmpt = []
for node in curLevel:
if node.left:
tmpt.append(node.left)
if node.right:
tmpt.append(node.right)
curLevel = tmpt
for node in curLevel:
node.left = TreeNode(val, node.left, None)
node.right = TreeNode(val, None, node.right)
return root
python3 解法, 执行用时: 52 ms, 内存消耗: 18.1 MB, 提交时间: 2022-08-05 10:18:27
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode:
if root == None:
return
if depth == 1:
return TreeNode(val, root, None)
if depth == 2:
root.left = TreeNode(val, root.left, None)
root.right = TreeNode(val, None, root.right)
else:
root.left = self.addOneRow(root.left, val, depth - 1)
root.right = self.addOneRow(root.right, val, depth - 1)
return root