Sunday, February 26, 2012

Min depth of a binary tree.


Given a binary tree, compute min depth of a leaf node.


Hint:
1. BFS
2. Recursive implementation
Which is better in time complexity?


BFS has the better complexity.
Recursive implementation has to see all the paths in the tree, the number of paths from root would be 2^d where d is the max depth of the tree.
BFS has to see only 2^d where d is the min depth of the tree.


Code input/output:
Tree values (BST):
int [] A = {12, 9, 15, 4, 10, 13, 20, 14, 25, 30};

Min Depth Recursive: 2
Min Depth BFS: 2
Max Depth: 4


No comments:

Post a Comment