简体   繁体   English

BST后序遍历中的打印深度

[英]Printing Depth in Post Order Traversal of BST

So right now I implemented in order traversal and I need to print the depth of where the node is. 所以现在我实现了顺序遍历,我需要打印节点所在的深度。 So if my tree is something like: 所以,如果我的树是这样的:

                                  5
                                 / \
                                2   9
                                \   /
                                 3 7

Then when it prints 3 it should have depth of 2. Where would I increment the depth if I am calling it recursively.And how would I decrement it if I am going up the tree? 然后当它打印3时它应该具有2的深度。如果我递归地调用它,我将在哪里增加深度。如果我在树上,我将如何减少它?

My code is 我的代码是

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
}

What I am asking is where I would increment level to show the appropriates depths of the nodes and why? 我要问的是,我将增加水平以显示节点的适当深度以及为什么?

There is no need to increment/decrement the level. 无需增加/减少级别。 When you make the recursive call, just pass in a value that is one larger than then current level, when the stack unwinds the level for the prior level will still be the value it was prior to the recursive call. 当你进行递归调用时,只传递一个大于当前级别的值,当堆栈展开先前级别的级别时,它仍然是递归调用之前的值。

Of course where you print the level will dictate the order that you see the level printed as you traverse the tree. 当然,在您打印关卡的位置将决定您在遍历树时看到打印关卡的顺序。

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
}

The level variable will help you keep a track of the depth. 水平变量将帮助您跟踪深度。 If you pass a current level + 1 value to the child level every time you make a recursive call, you will get the correct depth at every node. 如果每次进行递归调用时将当前级别+ 1值传递给子级别,则每个节点都将获得正确的深度。 Depending on whether you want the root depth to be 1 or 0, make the initial call with the root node and para 2 as 0 or 1. 根据您是希望根深度为1还是0,使用根节点进行初始调用,将第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
}

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

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