257. Binary Tree Paths
Problem description:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:1
2
3
4
5 1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
Solution:
The idea is to use dfs to find every leaf. The definition for leaf is it does not have left child or right child.
DFS1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19# 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 binaryTreePaths(self, root: TreeNode) -> List[str]:
def dfs(root, tmp, res):
if not root.left and not root.right:
res.append(tmp + str(root.val))
return
if root.left: dfs(root.left, tmp+ str(root.val) + "->", res)
if root.right: dfs(root.right, tmp+ str(root.val)+ "->", res)
if not root:
return []
res = []
dfs(root, "", res)
return res
BFS1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
# BFS
if not root:
return []
res = []
q = collections.deque([(root, "")])
while q:
node, tmp = q.popleft()
if not node.left and not node.right:
res.append(tmp + str(node.val))
if node.left:
q.append([node.left, tmp+str(node.val)+"->"])
if node.right:
q.append([node.right, tmp+str(node.val)+"->"])
return res
1 | /** |
time complexity: $O(n)$, because visit every node once
space complexity: $O(logn)$, height of the tree
reference:
https://goo.gl/RvfssD