I have using DFS and recursive to code this problem, shows below:
/**
* recursive
*/
public static List<List<Integer>> printAllPath(TreeNode root) {
List<List<Integer>> rst = new ArrayList<List<Integer>>();
helper(rst, new ArrayList<Integer>(), root);
return rst;
}
public static void helper(List<List<Integer>> rst, ArrayList<Integer> list,
TreeNode root) {
if (root == null) {
return;
}
list.add(root.val);
if (root.left == null && root.right == null) {
rst.add(new ArrayList<Integer>(list));
}
helper(rst, list, root.left);
helper(rst, list, root.right);
list.remove(list.size() - 1);
}
And after search for the internet, I found that the average time complexity of this algorithm is O(nlogn)
, and the worse case is O(n^2)
, is this right? and WHY? Can anyone kindly explain it?
I am not very familiar with analysis the time complexity of tree. In this problem, if I am using Queue
to implement, the time complexity should be O(n)
right? because I just iterate the whole tree once.
But how to analysis the time complexity of a tree that using recursive.?