-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBTfromPreOrder.java
More file actions
72 lines (59 loc) · 1.25 KB
/
BTfromPreOrder.java
File metadata and controls
72 lines (59 loc) · 1.25 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package tree;
public class BTfromPreOrder {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static int count_dash(String str, int i) {
int rv = 0;
while (i < str.length()) {
if (str.charAt(i) != '-')
break;
++i;
++rv;
}
return rv;
}
public static String extract(String str, int i) {
String rv = "";
while (i < str.length() && str.charAt(i) != '-') {
rv += str.charAt(i);
++i;
}
return rv;
}
public static int index;
public static TreeNode recoverFromPreorder(String S) {
index = 0;
if (S.length() == 0) {
return null;
} else {
return makeTree(S, 0);
}
}
public static TreeNode makeTree(String str, int depth) {
System.out.println(index);
if (index == str.length())
return null;
int dash = count_dash(str, index);
if (depth == dash) {
index+=dash;
String num=extract(str, index);
index+=num.length();
TreeNode node = new TreeNode(Integer.parseInt(num));
node.left=makeTree(str, depth+1);
node.right=makeTree(str, depth+1);
return node;
} else {
return null;
}
}
public static void main(String[] args) {
String str = "1-2--3--4-5--6--7";
TreeNode node = recoverFromPreorder(str);
}
}