简体   繁体   English

打印具有深度的二叉搜索树

[英]Print a binary search tree with depth

i need to print a binary search tree with depth and from high to low, depending on the depth increases the number of dashes before printing the node.我需要打印一个深度从高到低的二叉搜索树,根据深度在打印节点之前增加破折号的数量。 The root of the tree go with 0 dashes, her silbings go with one dash... I can print the tree without the dashes but i dont have idea how to print with the dashes.树的根 go 有 0 个破折号,她的 silbings go 有一个破折号......我可以打印没有破折号的树,但我不知道如何用破折号打印。 Im using C.我正在使用 C。 SORRY FOR MY BAD ENGLISH对不起,我的英语不好

There are two ways of achieving this.有两种方法可以实现这一目标。 Recursive or keeping the depth in nodes.递归或保持节点的深度。

1- You could use a recursive code like following 1-您可以使用如下递归代码

void printnode (bststruct *node, int depth)
{
    int i;
    for(i=1;i<=depth;i++) printf("-");
    printf("%d\n",node->value);
    if(node->left !=null) printnode(node->left,depth+1);
    if(node->right !=null) printnode(node->right,depth+1);
}

and in your main function or whichever function you run for this operation, just call printnode(root,0) .在您的主要 function 或您为此操作运行的任何 function 中,只需调用printnode(root,0)

2- Another way is to keep a dedicated value for depth in each node. 2- 另一种方法是在每个节点中保留一个专用的深度值。 If you are not going to use that value for any other purposes, just do the first option.如果您不打算将该值用于任何其他目的,请执行第一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM