1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution {
int depth, val;
public TreeNode addOneRow(TreeNode root, int val, int depth) { if (depth == 1) return new TreeNode(val, root, null); this.depth = depth; this.val = val; dfs(root, 1); return root; } private void dfs(TreeNode root, int cur) { if (root == null) return; if (cur == depth - 1) { TreeNode a = new TreeNode(val), b = new TreeNode(val); a.left = root.left; b.right = root.right; root.left = a; root.right = b; } else { dfs(root.left, cur + 1); dfs(root.right, cur + 1); } } }
|