Skip to content

Commit 884dbad

Browse files
author
Joseph Luce
authored
Create 144_binary_tree_preorder_traversal.md
1 parent 2f4efa0 commit 884dbad

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 144. Binary Tree Preorder Traversal
2+
3+
## Recursive Solution
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of elements in tree
7+
8+
Preorder traversal is node -> left -> right
9+
10+
```
11+
class Solution:
12+
def preorderTraversal(self, root: TreeNode) -> List[int]:
13+
def preorder_traversal_helper(root, result):
14+
if root is None:
15+
return
16+
result.append(root.val)
17+
preorder_traversal_helper(root.left, result)
18+
preorder_traversal_helper(root.right, result)
19+
20+
result = list()
21+
preorder_traversal_helper(root, result)
22+
return result
23+
```
24+
25+
## Iterative Solution
26+
- Runtime: O(N)
27+
- Space: O(N)
28+
- N = Number of elements in tree
29+
30+
This is one of the more easier iterative solutions out of the three traversals to understand.
31+
The current first in last out attributes of the stack conforms to the preorder traversal naturally.
32+
33+
```
34+
class Solution:
35+
def preorderTraversal(self, root: TreeNode) -> List[int]:
36+
stack = list([root])
37+
result = list()
38+
while len(stack) > 0:
39+
node = stack.pop()
40+
if node is not None:
41+
stack.append(node.right)
42+
stack.append(node.left)
43+
result.append(node.val)
44+
return result
45+
```

0 commit comments

Comments
 (0)