dfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (root == null) 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;
}
}
bfs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (root == null){
return null;
}
if (depth == 1){
return new TreeNode(val, root, null);
}
List<TreeNode> list = new ArrayList<>();
list.add(root);
for (int i = 1; i < depth - 1; i++){
List<TreeNode> temp = new ArrayList<>();
for (TreeNode node : list) {
if (node.left != null){
temp.add(node.left);
}
if (node.right != null){
temp.add(node.right);
}
}
list = temp;
}
for (TreeNode node : list) {
node.left = new TreeNode(val, node.left, null);
node.right = new TreeNode(val, null, node.right);
}
return root;
}
}

本文探讨了如何使用深度优先搜索(DFS)和广度优先搜索(BFS)算法在二叉树中实现添加新的一行的功能,通过实例展示了在不同深度条件下操作节点的技巧。
421

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



