Leetcode刷题-Java版本
1. 623. 在二叉树中增加一行
难度:中等
/**
* 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) {
List<TreeNode> pre = new LinkedList<>(),cur = new LinkedList<>();
if(depth != 1){
int dep = 1;
// dep 表示树的深度
pre.add(root);
while(!pre.isEmpty()){
for (TreeNode e : pre) {
if(e != null){
if(dep + 1 == depth){
TreeNode new_left = new TreeNode(val),new_right = new TreeNode(val);;
new_left.left = e.left;
e.left = new_left;
new_right.right = e.right;
e.right = new_right;
}else{
cur.add(e.left);
cur.add(e.right);
}
}
}
dep ++;
pre = new LinkedList<>(cur);
cur = new LinkedList<>();
}
}else{
TreeNode new_node = new TreeNode(val);
new_node.left = root;
root = new_node;
}
return root;
}
}