Given a binary tree, find the root-to-leaf path with the minimum length such that the path sum equals a target value S. If no such path exists, return an empty path.
graph TD
E(5)
E --- D(4) & H(8)
D --- K(11)
D ~~~ N1:::hidden
H --- M(13) & D2(4)
K --- G(7) & B(2)
D2 ~~~ N2:::hidden
D2 --- A(1)
linkStyle 0 stroke:#FF0000,stroke-width:2px;
linkStyle 2 stroke:#FF0000,stroke-width:2px;
linkStyle 7 stroke:#FF0000,stroke-width:2px;
classDef hidden display:none
1
2
3
4
5
6
Binary Tree: root =[5,4,8,11,null,13,4,7,2,null,null,null,1], target =22Output: [5,4,11,2]Explanation: There are two paths with sum S(22):1. Path [5,4,11,2]with length 42. Path [5,8,4,5]with length 4Among these, the shortest path is[5,4,11,2].
graph TD
A(8)
A --- B(4) & C(12)
B --- D(2) & E(6)
C --- F(5) & G(14)
E ~~~ N1:::hidden
E --- H(7)
G ~~~ N2:::hidden
H ~~~ N3:::hidden
linkStyle 1 stroke:#FF0000,stroke-width:2px;
linkStyle 4 stroke:#FF0000,stroke-width:2px;
classDef hidden display:none
1
2
3
4
5
6
Binary Tree: root =[8,4,12,2,6,10,14,null,null,7,null,5], target =25Output: [8,12,5]Explanation: There are two paths with sum 25:1. Path [8,4,6,7]with length 42. Path [8,12,5]with length 3So, we choose the path with length 3.
⏰ Time complexity: O(n) where n is the total number of nodes in the binary tree. Each node is visited once during DFS traversal.
🧺 Space complexity: O(h) where h is the height of the binary tree. This accounts for the recursive stack, which at maximum, will be proportional to the height of the tree.