-
Notifications
You must be signed in to change notification settings - Fork 1
/
26_November.java
50 lines (41 loc) · 1.42 KB
/
26_November.java
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
42
43
44
45
46
47
48
49
50
class Solution {
public static Node treeFromString(String s) {
// code here
StringBuilder str = new StringBuilder();
int i = 0;
int n = s.length();
while (i < n && Character.isDigit(s.charAt(i))) {
str.append(s.charAt(i));
i++;
}
Node root = new Node(Integer.parseInt(str.toString()));
Stack<Node> stack = new Stack<>();
stack.push(root);
while (i < n) {
switch (s.charAt(i)) {
case '(':
i++;
break;
case ')':
i++;
stack.pop();
break;
default:
str = new StringBuilder();
while (i < n && Character.isDigit(s.charAt(i))) {
str.append(s.charAt(i));
i++;
}
Node node = stack.peek();
Node temp = new Node(Integer.parseInt(str.toString()));
if (node.left != null) {
node.right = temp;
} else {
node.left = temp;
}
stack.push(temp);
}
}
return root;
}
}