我接受了以下无法回答的问题的考试:我们有一个二叉树,每个节点都有一定的高度(从底部)和一定的深度(从根)。我们从零开始计算;例如:对于具有单个子项的根的树,子项的深度将为1,高度将为0.
找到一个递归算法,打印所有中间节点,也就是说,当节点的高度等于其深度时。
给出的提示是:给d(深度)作为函数的参数,将高度作为返回值...
答案 0 :(得分:0)
Python实现,其中node是具有属性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
答案 1 :(得分: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);
}
}
将深度作为树的高度(考虑根的高度= 1)。