该说不说的,我觉得写的一气呵成挺完美
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if(depth == 1) {
TreeNode node = new TreeNode(val);
node.left = root;
return node;
}
dfs(root, 2, depth, val);
return root;
}
void dfs(TreeNode node, int nowDepth, int targetDepth, int val) {
if(node == null) {
return;
}
if(nowDepth == targetDepth) {
process(node, val);
}
dfs(node.left, nowDepth + 1, targetDepth, val);
dfs(node.right, nowDepth + 1, targetDepth, val);
}
/**
* 处理cur,为其添加两个值为val的子节点,并把原来的子树挂载在两端
*/
void process(TreeNode node, int val) {
TreeNode left = node.left;
TreeNode right = node.right;
node.left = new TreeNode(val);
node.right = new TreeNode(val);
node.left.left = left;
node.right.right = right;
}
}

这个博客介绍了一个Java方法,用于在一棵给定的二叉树的指定深度处插入一个新行,每个新节点的值都是固定的。通过深度优先搜索实现,将原有子树挂载到新节点的两侧。
391

被折叠的 条评论
为什么被折叠?



