Skip to content

Commit 3763ea7

Browse files
authored
Create Solution.java
1 parent ff161bf commit 3763ea7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
class Node{
12+
Node(TreeNode n,int d){
13+
node=n;
14+
depth=d;
15+
}
16+
TreeNode node;
17+
int depth;
18+
}
19+
public TreeNode addOneRow(TreeNode t, int v, int d) {
20+
if (d == 1) {
21+
TreeNode n = new TreeNode(v);
22+
n.left = t;
23+
return n;
24+
}
25+
Stack<Node> stack=new Stack<>();
26+
stack.push(new Node(t,1));
27+
while(!stack.isEmpty())
28+
{
29+
Node n=stack.pop();
30+
if(n.node==null)
31+
continue;
32+
if (n.depth == d - 1 ) {
33+
TreeNode temp = n.node.left;
34+
n.node.left = new TreeNode(v);
35+
n.node.left.left = temp;
36+
temp = n.node.right;
37+
n.node.right = new TreeNode(v);
38+
n.node.right.right = temp;
39+
40+
} else{
41+
stack.push(new Node(n.node.left, n.depth + 1));
42+
stack.push(new Node(n.node.right, n.depth + 1));
43+
}
44+
}
45+
return t;
46+
}
47+
}

0 commit comments

Comments
 (0)