-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructBinaryTreefromString536.java
More file actions
35 lines (30 loc) · 1.02 KB
/
Copy pathConstructBinaryTreefromString536.java
File metadata and controls
35 lines (30 loc) · 1.02 KB
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
package Tree;
import java.util.Stack;
public class ConstructBinaryTreefromString536 {
public TreeNode str2tree(String s) {
Stack<TreeNode> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
int j = i;
if (s.charAt(i) == ')') {
stack.pop();
}
if (s.charAt(i) == '-' || Character.isDigit(s.charAt(i))) {
while (i + 1 < s.length() && Character.isDigit(s.charAt(i))) {
i++;
}
int value = Integer.valueOf(s.substring(j, i + 1));
TreeNode node = new TreeNode(value);
if (!stack.isEmpty()) {
if (stack.peek().left != null) {
stack.peek().right = node;
}
else {
stack.peek().left = node;
}
}
stack.push(node);
}
}
return (stack.isEmpty()) ? null : stack.pop();
}
}