File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments