All Root to Leaf Paths
Given a binary tree, return a 2d dimensional vector that contains all the possible root-to-leaf paths of the tree.
Ex.
How it works
I keep two vectors, one 1d and the other 2d. Both are passed as references because I dont want them to change on the call stack.
I run a pre-order dfs traversal - each time checking if I've encountered a leaf. If so, I will need to append the current vector to the 2d main one. I then pop_back because I know that the next path in the tree will contain the previous vector, with at least the leaf removed. (The paths share a common ancestor).
Python Version:
Notice the use of the deepcopy
. This was necessary because if we were to otherwise pass in the address of cur
, then future pop()'s
would internally mess with other paths.
Last updated