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.

DFS

1
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

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(!root) return vector<string>();
string tmp= "";
helper(res, tmp, root);
return res;
}

void helper(vector<string>& res, string tmp, TreeNode* root){
if(!root->left && !root->right) //reach a leaf
res.push_back(tmp+to_string(root->val));
if(root->left) helper(res, tmp+to_string(root->val)+"->", root->left);
if(root->right) helper(res, tmp+to_string(root->val)+"->", root->right);
}

};

time complexity: $O(n)$, because visit every node once
space complexity: $O(logn)$, height of the tree
reference:
https://goo.gl/RvfssD