-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1028-Recover-a-Tree-From-Preorder-Traversal.java
More file actions
56 lines (45 loc) · 1.24 KB
/
1028-Recover-a-Tree-From-Preorder-Traversal.java
File metadata and controls
56 lines (45 loc) · 1.24 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode recoverFromPreorder(String s) {
Stack<TreeNode> st= new Stack<>();
int ind=0;
while(ind<s.length()){
int dep=0;
while(ind<s.length() && s.charAt(ind)=='-'){
dep+=1;
ind+=1;
}
int val=0;
while(ind<s.length() && Character.isDigit(s.charAt(ind))){
val= val*10+ (s.charAt(ind)-'0');
ind+=1;
}
TreeNode node= new TreeNode(val);
while(st.size()>dep) st.pop();
if(!st.isEmpty()){
if(st.peek().left==null){
st.peek().left= node;
}else{
st.peek().right= node;
}
}
st.push(node);
}
while(st.size()>1) st.pop();
return st.peek();
}
}