Skip to content

Commit c217992

Browse files
authored
Create Solution.py
1 parent 8a4905e commit c217992

File tree

1 file changed

+39
-0
lines changed
  • solution/1000-1099/1028.Recover a Tree From Preorder Traversal

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:
9+
stack = []
10+
depth = 0
11+
num = 0
12+
S = traversal
13+
14+
i = 0
15+
while i < len(S):
16+
depth = 0
17+
while i < len(S) and S[i] == '-':
18+
depth += 1
19+
i += 1
20+
21+
num = 0
22+
while i < len(S) and S[i].isdigit():
23+
num = num * 10 + int(S[i])
24+
i += 1
25+
26+
# Create the new node
27+
newNode = TreeNode(num)
28+
29+
while len(stack) > depth:
30+
stack.pop()
31+
32+
if stack:
33+
if not stack[-1].left:
34+
stack[-1].left = newNode
35+
else:
36+
stack[-1].right = newNode
37+
38+
stack.append(newNode)
39+
return stack[0] if stack else None

0 commit comments

Comments
 (0)