Why are there only log(N) recursive calls made in this tree traversal?

Viewed 363

The following code is the solution to this problem: "Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked list".

void createLevelLinkedList(TreeNode root, ArrayList<LinkedList<TreeNode>>lists, int level) {

   if(root == null) return; //base case

   LinkedList<TreeNode> list = null;
   if (lists.size()==level){ //Level not contained in list
      list = new LinkedList<TreeNode>();
      lists.add(list);
   } else{
     list = lists.get(level);
   }

   list.add(root);
   createLevelLinkedlist(root.left, lists, level+1);
   createLevelLinkedList(root.right, lists, level+1);
}

ArrayList<LinkedList<TreeNode>> createLevelLinkedList(TreeNode root){

   ArrayList<LinkedList<TreeNode>> lists = new ArrayList<LinkedList<TreeNode>>();

   createLevelLinkedlist(root, lists, 0);
   return lists;

}

According to the solution, this code has a runtime of O(N) but uses O(log N) recursive calls. Why would there only be O(log N) recursive calls? It looks like within each call, there are always two new recursive calls made to root.left and root.right, so shouldn't there be O(N) recursive calls? One for each node in the tree?

"The solution uses O(log N) recursive calls (in a balanced tree), each of which adds a new level to the stack"

Sorry, am really confused, would appreciate an explanation thanks!

1 Answers

It talks about the depth of recursive calls. And if you closely look at it, for a balanced binary tree, the number of times it will recurse is the same as the height of tree which is log N. When a function calls itself, think of it as a chain with 2 links and no individual chain can have more than log N links.

What you're talking about is the number of function calls which is N. But the maximum depth of recursion(nested function calls) is log N.

Related