|
4 | 4 | * int val;
|
5 | 5 | * TreeNode left;
|
6 | 6 | * TreeNode right;
|
7 |
| - * TreeNode(int x) { val = x; } |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
8 | 14 | * }
|
9 | 15 | */
|
10 | 16 | class Solution {
|
11 |
| - public TreeNode recoverFromPreorder(String S) { |
12 |
| - Map<Integer, TreeNode> map = new HashMap<>(); |
| 17 | + public TreeNode recoverFromPreorder(String traversal) { |
| 18 | + Stack<TreeNode> stack = new Stack<>(); |
13 | 19 | int idx = 0;
|
14 |
| - int n = S.length(); |
15 |
| - |
16 |
| - while (idx < n) { |
17 |
| - int level = 0; |
18 |
| - StringBuilder sb = new StringBuilder(); |
19 |
| - |
20 |
| - while (idx < n && S.charAt(idx) == '-') { |
21 |
| - level++; |
| 20 | + while (idx < traversal.length()) { |
| 21 | + int depth = 0; |
| 22 | + while (idx < traversal.length() && traversal.charAt(idx) == '-') { |
| 23 | + depth++; |
22 | 24 | idx++;
|
23 | 25 | }
|
24 |
| - |
25 |
| - while (idx < n && Character.isDigit(S.charAt(idx))) { |
26 |
| - sb.append(S.charAt(idx++)); |
| 26 | + int value = 0; |
| 27 | + while (idx < traversal.length() && Character.isDigit(traversal.charAt(idx))) { |
| 28 | + value = value * 10 + Character.getNumericValue(traversal.charAt(idx++)); |
27 | 29 | }
|
28 |
| - |
29 |
| - TreeNode currNode = new TreeNode(Integer.parseInt(sb.toString())); |
30 |
| - map.put(level, currNode); |
31 |
| - if (level > 0) { |
32 |
| - TreeNode parent = map.get(level - 1); |
33 |
| - if (parent.left == null) { |
34 |
| - parent.left = currNode; |
35 |
| - } |
36 |
| - else { |
37 |
| - parent.right = currNode; |
| 30 | + TreeNode node = new TreeNode(value); |
| 31 | + while (stack.size() > depth) { |
| 32 | + stack.pop(); |
| 33 | + } |
| 34 | + if (!stack.isEmpty()) { |
| 35 | + if (stack.peek().left == null) { |
| 36 | + stack.peek().left = node; |
| 37 | + } else { |
| 38 | + stack.peek().right = node; |
38 | 39 | }
|
39 | 40 | }
|
| 41 | + stack.push(node); |
| 42 | + } |
| 43 | + while (stack.size() > 1) { |
| 44 | + stack.pop(); |
40 | 45 | }
|
41 |
| - |
42 |
| - return map.get(0); |
| 46 | + return stack.peek(); |
43 | 47 | }
|
44 | 48 | }
|
0 commit comments