简体   繁体   中英

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?

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. 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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