Thursday, January 5, 2012

Find Depth of a binary tree

Problem: Given the root of a binary tree, return its depth. A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2

Approach: We can use post order traversal here. The simple formula of depth is Max(Depth(left), Depth(right) + 1. Obviously, if root itself is null then the depth is 0.


Implementation in C#:

    public int MaxDepth(TreeNode root)
    {
        if (root == null)
        {
            return 0;
        }
        return Math.Max(this.MaxDepth(root.left),
                        this.MaxDepth(root.right)) + 1;
    }


Complexity: O(n)

Tuesday, January 3, 2012

Google Question: Find nth minimum in Binary Search Tree.

1. Without extra field in Node structure --

Do inorder traversal and count number of node visited. When count is equal to n return the node.
void BSTree::findNthElem(Node* node, int& n, int& retval)
{
if(!node && n)
retval = -1;
else if(n)
{
findNthElem(node->left, n, retval);
if(n)
{
n = n - 1;
if(n == 0)
retval = node->data;
findNthElem(node->right, n, retval);
}
}
}