-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Tree Preorder Traversal.py
61 lines (43 loc) · 1.4 KB
/
Binary Tree Preorder Traversal.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
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
# Time complexity - O(N)
# Space complexity - O(N)
# 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: Optional[TreeNode]) -> List[int]:
result = []
return self.findPreorder(root,result)
def findPreorder(self,root,result):
if root is None:
return result
else:
result.append(root.val)
result = self.findPreorder(root.left,result)
result = self.findPreorder(root.right,result)
return result
# Time complexity - O(N)
# Space complexity - O(N)
# 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: Optional[TreeNode]) -> List[int]:
if root is None:
return []
result = []
stack = []
stack.append(root)
while stack:
current = stack.pop()
result.append(current.val)
if current.right != None:
stack.append(current.right)
if current.left != None:
stack.append(current.left)
return result