- Leetcode 257 Binary tree paths
- Level: Easy
- Link
My approach
Classic dfs problem with a tree data structure
- Check if a root has left or right leaf
- If either the left or right leaf exists:
- perform dfs recursively with the left/right leaf set as the root
- If none of the left or right leaf exists:
- Append the path to the answer array
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
def dfs(node, path):
path += '->'
path += str(node.val)
if not node.left and not node.right:
return ans.append(path[2:])
if node.left:
dfs(node.left, path)
if node.right:
dfs(node.right, path)
ans = []
dfs(root, "")
return ans
'개발공부 > algorithm' 카테고리의 다른 글
[Leetcode][python] 929: Unique email addresses (0) | 2021.04.28 |
---|---|
[Leetcode][python] 1161: Maximum Level of sum of a binary tree - BFS (0) | 2021.04.27 |
[Leetcode][python] 733: flood fill - bfs (0) | 2021.04.25 |
[Leetcode][python] 690 - Employee importance - DFS (0) | 2021.04.25 |
[백준][python] 4889 안정적인 문자열 - Greedy (0) | 2021.04.25 |