LeetCode #113 Path Sum II
Problem
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
Solution
Use recursively DFS for searching matching path.
Complexity
Because each node will be iterated once, it takes O(n) time if n
denotes to counts of nodes in this tree.
For space complexity, the calls in calling stack may reach h
if h
denotes to the length of the deepest path in the tree. So it’s space complexity is O(h). Or you can say O(logn) because h
is bounded by logn
.