forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
25 lines (25 loc) · 822 Bytes
/
Solution.py
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
# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
while root:
if root.left is None:
res.append(root.val)
root = root.right
else:
pre = root.left
while pre.right and pre.right != root:
pre = pre.right
if pre.right is None:
res.append(root.val)
pre.right = root
root = root.left
else:
pre.right = None
root = root.right
return res