-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1028.Recover-a-Tree-From-Preorder-Traversal.py
More file actions
55 lines (47 loc) · 1.69 KB
/
1028.Recover-a-Tree-From-Preorder-Traversal.py
File metadata and controls
55 lines (47 loc) · 1.69 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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:
# a global index to traverse through the input array
idx = 0
val = 0
depth = -1
dummy = TreeNode()
def parseInput():
nonlocal idx, val, depth
# only parse the input string when necessary
if idx < len(traversal) and val == 0:
# yes we need to parse the next node
depth = 0
while traversal[idx] == '-':
depth += 1
idx += 1
val = 0
while idx < len(traversal) and traversal[idx].isdigit():
val = val * 10 + int(traversal[idx])
idx += 1
def dfs(parent, parent_depth) -> None:
nonlocal idx, val, depth
if not parent:
return
parseInput()
# next we check whether we need to backtrack
if parent_depth == depth - 1:
if not parent.left:
parent.left = TreeNode(val)
val = 0
depth = -1
dfs(parent.left, parent_depth+1)
if parent_depth == depth - 1:
if not parent.right:
parent.right = TreeNode(val)
val = 0
depth = -1
dfs(parent.right, parent_depth+1)
return
dfs(dummy, -1)
return dummy.left