Skip to content

Commit 350d98c

Browse files
committed
upload solutions 144 & 145
1 parent b65ddb1 commit 350d98c

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# 144 - Binary Tree Preorder Traversal
2+
3+
Difficulty: easy
4+
Done: Yes
5+
Last edited: March 13, 2022 10:59 PM
6+
Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
7+
Topic: recursion, tree
8+
9+
## Problem
10+
11+
---
12+
13+
Given the `root` of a binary tree, return *the preorder traversal of its nodes' values*.
14+
15+
```
16+
Input: root = [1,null,2,3]
17+
Output: [1,2,3]
18+
```
19+
20+
## Solution
21+
22+
---
23+
24+
Pre-order traversal requires order of parent -> left child -> right child. Can do so recursively, and return empty array if input is none
25+
26+
## Code
27+
28+
---
29+
30+
```python
31+
# Definition for a binary tree node.
32+
# class TreeNode:
33+
# def __init__(self, val=0, left=None, right=None):
34+
# self.val = val
35+
# self.left = left
36+
# self.right = right
37+
class Solution:
38+
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
39+
40+
# if we have no nodes in input return empty list
41+
if not root:
42+
return []
43+
44+
# pre-order traversal requires order of parent -> left child -> right child
45+
# can do so recursively
46+
47+
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
48+
```
49+
50+
## Time Complexity
51+
52+
---
53+
54+
The time complexity is O(n)*O*(*n*) because the recursive function is $T(n)=2⋅T(n/2)+1T(n)=2⋅T(n/2)+1$.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 145 - Binary Tree Postorder Traversal
2+
3+
Difficulty: easy
4+
Done: Yes
5+
Last edited: March 13, 2022 10:59 PM
6+
Link: https://leetcode.com/problems/binary-tree-postorder-traversal/
7+
Topic: recursion, tree
8+
9+
## Problem
10+
11+
---
12+
13+
Given the `root` of a binary tree, return *the preorder traversal of its nodes' values*.
14+
15+
```
16+
Input: root = [1,null,2,3]
17+
Output: [3,2,1]
18+
```
19+
20+
## Solution
21+
22+
---
23+
24+
post order goes as left child -> right child -> root
25+
26+
## Code
27+
28+
---
29+
30+
```python
31+
# Definition for a binary tree node.
32+
# class TreeNode:
33+
# def __init__(self, val=0, left=None, right=None):
34+
# self.val = val
35+
# self.left = left
36+
# self.right = right
37+
class Solution:
38+
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
39+
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] if root is not None else []
40+
```
41+
42+
## Time Complexity
43+
44+
---
45+
46+
The time complexity is O(n)*O*(*n*) because the recursive function is $T(n)=2⋅T(n/2)+1T(n)=2⋅T(n/2)+1$.

0 commit comments

Comments
 (0)