MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/hard/_1028/Solution.java:15–79  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2020/06/19 desc :

Source from the content-addressed store, hash-verified

13 * </pre>
14 */
15public class Solution {
16// public TreeNode recoverFromPreorder(String S) {
17// char[] chars = S.toCharArray();
18// int len = chars.length;
19// List<TreeNode> levels = new LinkedList<>();
20// for (int i = 0; i < len; ) {
21// int level = 0, val = 0;
22// while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢
23// ++i;
24// ++level;
25// }
26// while (i < len && chars[i] != '-') { // 获取节点的值
27// val = val * 10 + chars[i++] - '0';
28// }
29// TreeNode curNode = new TreeNode(val);
30// if (level > 0) {
31// TreeNode parent = levels.get(level - 1);
32// if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。
33// parent.left = curNode;
34// } else {
35// parent.right = curNode;
36// }
37// }
38// levels.add(level, curNode); // 因为是前序遍历(根-左-右),也就是右覆盖左时,此时左树已遍历完成,故无需考虑覆盖问题
39// }
40// return levels.get(0);
41// }
42
43 public TreeNode recoverFromPreorder(String S) {
44 char[] chars = S.toCharArray();
45 int len = chars.length;
46 LinkedList<TreeNode> stack = new LinkedList<>();
47 for (int i = 0; i < len; ) {
48 int level = 0, val = 0;
49 while (chars[i] == '-') { // 获取所在层级,Character.isDigit() 会比较慢
50 ++i;
51 ++level;
52 }
53 while (i < len && chars[i] != '-') { // 获取节点的值
54 val = val * 10 + chars[i++] - '0';
55 }
56 TreeNode curNode = new TreeNode(val);
57 while (stack.size() > level) { // 栈顶不是父亲,栈顶出栈
58 stack.removeLast();
59 }
60 if (level > 0) {
61 TreeNode parent = stack.getLast();
62 if (parent.left == null) { // 如果节点只有一个子节点,那么保证该子节点为左子节点。
63 parent.left = curNode;
64 } else {
65 parent.right = curNode;
66 }
67 }
68 stack.addLast(curNode);
69 }
70 return stack.get(0);
71 }
72

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected