携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情
给定一个二叉树的根 root 和两个整数 val 和 depth ,在给定的深度 depth 处添加一个值为 val 的节点行。
注意,根节点 root 位于深度 1 。
加法规则如下:
- 给定整数
depth,对于深度为depth - 1的每个非空树节点cur,创建两个值为val的树节点作为cur的左子树根和右子树根。 cur原来的左子树应该是新的左子树根的左子树。cur原来的右子树应该是新的右子树根的右子树。- 如果
depth == 1意味着depth - 1根本没有深度,那么创建一个树节点,值val作为整个原始树的新根,而原始树就是新根的左子树。
示例 1:
输入: root = [4,2,6,3,1,5], val = 1, depth = 2
输出: [4,1,1,2,null,null,6,3,1,5]
示例 2:
输入: root = [4,2,null,3,1], val = 1, depth = 3
输出: [4,2,null,1,1,3,null,null,1]
深度优先搜索
当输入 为 时,需要创建一个新的 ,并将原 作为新 的左子节点。当 为 时,需要在 下新增两个节点 和 作为 的新子节点,并把原左子节点作为 的左子节点,把原右子节点作为 的右子节点。当 大于 时,需要继续递归往下层搜索,并将 减去 ,直到搜索到 为 。
var addOneRow = function(root, val, depth) {
if (!root) {
return null;
}
if (depth === 1) {
return new TreeNode(val, root, null);
}
if (depth === 2) {
root.left = new TreeNode(val, root.left, null);
root.right = new TreeNode(val, null, root.right);
} else {
root.left = addOneRow(root.left, val, depth - 1);
root.right = addOneRow(root.right, val, depth - 1);
}
return root;
};
广度优先搜索
与深度优先搜索类似,我们用广度优先搜索找到要加的一行的上一行,然后对这一行的每个节点 ,都新增两个节点 和 作为 的新子节点,并把原左子节点作为 的左子节点,把原右子节点作为 的右子节点。
var addOneRow = function(root, val, depth) {
if (depth === 1) {
return new TreeNode(val, root, null);
}
let curLevel = [];
curLevel.push(root);
for (let i = 1; i < depth - 1; i++) {
const tmp = [];
for (const node of curLevel) {
if (node.left) {
tmp.push(node.left);
}
if (node.right) {
tmp.push(node.right);
}
}
curLevel = tmp;
}
for (const node of curLevel) {
node.left = new TreeNode(val, node.left, null);
node.right = new TreeNode(val, null, node.right);
}
return root;
};