4
private int Depth(TreeNode node)
{
    if (node == null)
    {
        return -1;
    }
    else
    {
        return 1 + Math.Max(Depth(node.LeftNode),Depth(node.RightNode));
    }
}

I wrote method to find deepest node, but I am not sure about this method.
Is this the correct way to find deepest node?

Marco
  • 53,280
  • 13
  • 123
  • 142
Desire
  • 523
  • 4
  • 12
  • 28

2 Answers2

3

(Assuming that what you want to get is height of the tree including node given as parameter)

For empty tree (node == null) you will get depth of -1. For tree with 1 node you will receive:

1 + max(-1, -1) = 0

and so on, returning 0 should fix the problem, but general idea is fine.

As for optimization... if only thing you know about this tree is that it's binary tree, then this is the best you can get without caching heights in nodes.

As for finding closest leaf you could use BFS algorithm to do it efficiently, because it will go and discover nodes horizontally, and then then you can stop when you discover 1st leaf.

BFS pseudocode:

nodes.enqueue( tuple(node, 1)) //enqueue node with height == 1
while(nodes.count > 0)
{
  (node, h) = nodes.dequeue()
  if (node.left == null && node.right == null) return h; //If it's first leaf we've found, return it's height.

  //Enqueue our childs with their height
  if (node.left != null)
    nodes.enqueue(node.left, h+1);
  if (node.right != null)
    nodes.enqueue(node.right, h+1);
}
Marcin Deptuła
  • 11,171
  • 2
  • 30
  • 40
  • then what about minimum depth node? I think the node which is nearer/closest to root is minimum depth node. – Desire Dec 05 '11 at 12:13
  • 1
    Hmm, You are asking for deepest node, how do you understand "deepest"? In my understanding it is the node which has as many parents as possible going up to the root, which makes it the node with highest depth. – Marcin Deptuła Dec 05 '11 at 12:16
1

The deepest node of a BST is called the height.

Here you may see how to calculate the height of a BST.

Basically what you have is right.

Community
  • 1
  • 1
Dimme
  • 4,247
  • 3
  • 27
  • 49
  • then what about minimum depth node? I think the node which is nearer/closest to root is minimum depth node – Desire Dec 05 '11 at 12:10
  • 1
    What you want is probably the distance to the first leaf closest to the root. You can achieve that by stopping the recursion and returning the value as soon as you reach the first null. – Dimme Dec 05 '11 at 12:12
  • would you please explain it more clearly, by iterative method – Desire Dec 05 '11 at 12:35