BST的后遍历中的打印深度

时间:2019-03-17 01:40:32

标签: c binary-search-tree postorder

所以现在我实现了顺序遍历,并且需要打印节点所在的深度。因此,如果我的树是这样的:

                                  5
                                 / \
                                2   9
                                \   /
                                 3 7

然后在打印3时,其深度应为2。 如果递归调用深度,该在哪里增加?如果沿着树向上倾斜,该如何减小深度?

我的代码是

void post_order(BST* root,int level)
    if(root == NULL){
        return;
    }
    post_order(root -> left,level); 
    post_order(root -> right, level);
    //Here I would print the node info and depth
}

我要问的是我将在哪里增加级别以显示适当的节点深度,为什么?

2 个答案:

答案 0 :(得分:2)

无需增加/减少电平。当您进行递归调用时,只需传递一个比当前级别大一的值,当堆栈展开时,先前级别的级别仍将是递归调用之前的值。

当然,您在打印水准仪的位置将指示遍历树时看到的水准仪打印顺序。

void post_order(BST* root,int level)
    if(root == NULL){
        return;
    }
    post_order(root -> left,level + 1); 
    post_order(root -> right, level + 1);
    //Here I would print the node info and depth
}

答案 1 :(得分:1)

level变量将帮助您跟踪深度。如果每次进行递归调用时都将当前级别+ 1的值传递给子级别,则将在每个节点上获得正确的深度。根据您希望根深度为1还是0,以根节点和para 2为0或1进行初始调用。

void post_order(BST* root,int level)
if(root == NULL){
    return;
}
post_order(root -> left,level+1); 
post_order(root -> right, level+1);
//print node info, depth = level
}
相关问题