0

I had an exam with the following question I couldn't answer: We have a binary tree where each node has a certain height(from bottom) and a certain depth(from root). We start counting both from zero; for example: For a tree with a root with a single child, the depth of the child would be 1 and the height would be 0.

Find an recursive algorithm which prints all of the median nodes, that is, when a node's height is equal to its depth.

A hint was given which was: Give d(depth) as an argument for the function and the height as a return value...

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Gene Frank
  • 23
  • 1
  • 1
  • 4

2 Answers2

0

Python implementation where node is an object with attribute children.

def R(node, d):
  if not node.children: # No children, leaf node
    height = 0
  else:
    height = max( R(child, d+1) for child in node.children ) + 1
  if height == d:
    print node  # Or some node.id
  return height

R(root, 0)  # Call with a root node
Ante
  • 5,350
  • 6
  • 23
  • 46
0
void medianInTree(class tree* root, int depth, int height)
{

    if(root)
    {
         if(height == depth)
             cout<<"   "<<root->data;
         medianInTree(root->left, depth-1, height+1);
         medianInTree(root->right, depth-1, height+1);
    }
}

Pass depth as height of tree(considering height of root=1).

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
instance
  • 1,366
  • 15
  • 23