Finding Depth of Binary Tree - c++

I am having trouble understanding this maxDepth code. Any help would be appreciated. Here is the snippet example I followed.
int maxDepth(Node *&temp)
{
if(temp == NULL)
return 0;
else
{
int lchild = maxDepth(temp->left);
int rchild = maxDepth(temp->right);
if(lchild <= rchild)
return rchild+1;
else
return lchild+1;
}
}
Basically, what I understand is that the function recursively calls itself (for each left and right cases) until it reaches the last node. once it does, it returns 0 then it does 0+1. then the previous node is 1+1. then the next one is 2+1. if there is a bst with 3 left childs, int lchild will return 3. and the extra + 1 is the root. So my question is, where do all these +1 come from. it returns 0 at the last node but why does it return 0+1 etc. when it goes up the left/right child nodes? I don't understand why. I know it does it, but why?

Consider this part (of a bigger tree):
A
\
B
Now we want to calculate the depth of this treepart, so we pass pointer to A as its param.
Obviously pointer to A is not NULL, so the code has to:
call maxDepth for each of A's children (left and right branches). A->right is B, but A->left is obviously NULL (as A has no left branch)
compare these, choose the greatest value
return this chosen value + 1 (as A itself takes a level, doesn't it?)
Now we're going to look at how maxDepth(NULL) and maxDepth(B) are calculated.
The former is quite easy: the first check will make maxDepth return 0. If the other child were NULL too, both depths would be equal (0), and we have to return 0 + 1 for A itself.
But B is not empty; it has no branches, though, so (as we noticed) its depth is 1 (greatest of 0 for NULLs at both parts + 1 for B itself).
Now let's get back to A. maxDepth of its left branch (NULL) is 0, maxDepth of its right branch is 1. Maximum of these is 1, and we have to add 1 for A itself - so it's 2.
The point is the same steps are to be done when A is just a part of the bigger tree; the result of this calculation (2) will be used in the higher levels of maxDepth calls.

Depth is being calculated using the previous node + 1

All the ones come from this part of the code:
if(lchild <= rchild)
return rchild + 1;
else
return lchild + 1;
You add yourself +1 to the results obtained in the leaves of the tree. These ones keep adding up until you exit all the recursive calls of the function and get to the root node.

Remember in binary trees a node has at most 2 children (left and right)
It is a recursive algorithm, so it calls itself over and over.
If the temp (the node being looked at) is null, it returns 0, as this node is nothing and should not count. that is the base case.
If the node being looked at is not null, it may have children. so it gets the max depth of the left sub tree (and adds 1, for the level of the current node) and the right subtree (and adds 1 for the level of the current node). it then compares the two and returns the greater of the two.
It dives down into the two subtrees (temp->left and temp->right) and repeats the operation until it reaches nodes without children. at that point it will call maxDepth on left and right, which will be null and return 0, and then start returning back up the chain of calls.
So if you you have a chain of three nodes (say, root-left1-left2) it will get down to left2 and call maxDepth(left) and maxDepth(right). each of those return 0 (they are null). then it is back at left2. it compares, both are 0, so the greater of the two is of course 0. it returns 0+1. then we are at left1 - repeats, finds that 1 is the greater of its left n right (perhaps they are the same or it has no right child) so it returns 1+1. now we are at root, same thing, it returns 2+1 = 3, which is the depth.

Because the depth is calculated with previous node+1

To find Maximum depth in binary tree keep going left and Traveres the tree, basically perform a DFS
or
We can find the depth of the binary search tree in three different recursive ways
– using instance variables to record current depth and total depth at every level
– without using instance variables in top-bottom approach
– without using instance variables in bottom-up approach

The code snippet can be reduced to just:
int maxDepth(Node *root){
if(root){ return 1 + max( maxDepth(root->left), maxDepth(root->right)); }
return 0;
}
A good way of looking at this code is from the top down:
What would happen if the BST had no nodes? We would have root = NULL and the function would immediately return an expected depth of 0.
Now suppose the tree was populated with a number of nodes. Starting at the top, the if condition would be true for the root node. We then ask, what is the max depth of the LEFT SUB TREE and the RIGHT SUB TREE by passing the root of those sub trees to maxDepth. Both the LST and the RST of the root are one level deeper than the root, so we must add one to get the depth of the tree at root of the tree passed to the function.

i think this is the right answer
int maxDepth(Node *root){
if(root){ return 1 + max( maxDepth(root->left), maxDepth(root->right)); }
return -1;
}

Related

Extract the root from a max heap

I am struggling to write a recursive algorithm to extract the max(root) from a max heap.
The heap is constructed as a tree.
I know that I should swap the last node with the root and push it down recursively. But there is no pseudocode on the internet or stack overflow to deal with trees.
The extract algorithms that I have seen are based on arrays.
So let's say that I find the right most leaf.
Is there any solution that you can suggest?
void find_last(heap_node* root,int level,int* last_level,bool isRight,heap_node** res){
if(root == NULL)
return;
if(isRight && !root->left && !root->right && level > *last_level){
*res = root;
*last_level = level;
return;
}
find_last(root->right,level+1,last_level,true,res);
find_last(root->left,level+1,last_level,false,res);
}
And i made a function call like this
heap_node* last = NULL;
int last_level = -1;
find_last(root,0,&last_level,false,&last);
That is the code of finding the deepest right node.
And it is not working :D
Efficiently finding the last node in a heap that's implemented as a tree requires that you maintain a count of nodes. That is, you know how many items are in the heap.
If you know how many items are in the heap, then you get the binary representation of the number and use that to trace through the tree to the last node. Let me give you an example. You have this heap:
1
/ \
2 3
/ \ / \
4 5 6
There are 6 items in the heap. The binary representation is 110.
Now, moving from right to left in the binary representation. You remove the first '1' and you're at the root node. The rule is that you go right if the digit is '1', and left if the digit is '0'. At the root node, you have 10. So you go right and remove that digit, leaving you with 0. You're at the node marked "3". The remaining digit is 0, so you go left. That puts you at the last node in the heap.
The algorithm for sifting down through the heap is the same regardless of whether the heap is represented as an array or as a tree. The actual steps you take to swap nodes is different, of course. When swapping nodes, you have to be careful to set the child pointers correctly. One place people often forget is when swapping the root node with the last node.
My suggestion is that you code this up and then single-step in the debugger to make sure that you have the pointer assignments right.

How the double recursion works in C/C++ - for example depth of a binary tree?

Recursion doesn't strike naturally to me. A few programs, which I could understand was Factorial, where factorial of n is n * factorial(n-1). Similarly, fibonacci series - Fn = Fn-1 + Fn-2. Also, a bst- insert, search. All these recursion functions have one thing common - a condition to return the concrete value. Otherwise, it will call itself with a different parameter. Once the concrete value is returned, all the calls are unfolded. However, I am not able to understand the programs where the recursion is one after the other. What happens over there. How can I think on those lines naturally? For example - here is the program -
What is the significance of the following lines?
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}
While searching the tree, the condition that returns a concrete value is if (node==NULL) and the concrete value returned is 0, which is a tree of depth 0. Consider the following tree (from wikipedia)
Starting at node 8, the code will recurse to node 3, and then to node 1. When it tries to recurse to the left child of node 1, it will find NULL and return 0. Then it will try the right child of node 1, which will also return 0. At this point node 1 comes to the if statement
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
Since both lDepth and rDepth are 0, node 1 returns 1 to node 3. Then node 3 recurses to node 6, and so on.
Each call to maxDepth(node->left) will result in an immediate call to maxDepth(node->left), until there it nothing left (no pun intended) on the left most side of the tree. Then the last call returns and there will be a call to maxDepth(node->right).
This is a so-called 'depth-first' traversal, in that we go as far up the tree as possible and then visit the leaves on each branch until we're done on the branch and then we back-up to the fork.
Perhaps the best way to understand this code is to draw a picture of a small binary tree, and step through the code to see what will happen.
Mentally, it may help to separate the logic into two parts. If you have a pointer possibly to a node in a singly-linked list, and define the depth of a NULL pointer as being 0, then you can say the depth of any other node is one more than the depth of the node to which it links.
{node3 p_next_->}---->{node2 p_next_->}---->{node1 p_next_=nullptr}
So, the code for this would be:
int depth(Node* p)
{
if (p == NULL) return 0;
return depth(p->p_next_) + 1;
}
Then, your question is about a binary tree... the logic is similar but each time you work out the depth of a node, you're saying "well, this node may have a right and/or a left hierarchy of nodes under it... my depth is one more than the greater of their depths".
Alternatively, it might help to think of a family, say fred has two children sue and max, and so on....
fred
/ \
sue max
/ \
sally charlie
/
june
Here, working out the depth of say sue is a bit like asking "is she a child (depth 1), a parent (depth 2), a grandparent (depth 3), a great-grandparent (depth 4)?"
We can see she's sally's mother (depth 2 on that side), but she's june's grandmother (depth 3) on that side.
We can work out that answer of 3 systematically by saying sue's depth is one more than the deepest of sally and charlie's, and sally's got no kids (their imaginary depth is 0) so she's depth 1 so sue'2 at least 2, but charlie's one more than june who's one more than her imaginarykids (depth 0) i.e. june's 1 so charlie's 2 so sue's actually 3, being more than the count from sally's side.

Red-Black Tree Height using Recursion

I have these following methods to get the height of a red black tree and this works (I send the root). Now my question is, how is this working? I have drawn a tree and have tried following this step by step for each recursion call but I can't pull it off.
I know the general idea of what the code is doing, which is going through all the leaves and comparing them but can anyone give a clear explanation on this?
int RedBlackTree::heightHelper(Node * n) const{
if ( n == NULL ){
return -1;
}
else{
return max(heightHelper(n->left), heightHelper(n->right)) + 1;
}
}
int RedBlackTree::max(int x, int y) const{
if (x >= y){
return x;
}
else{
return y;
}
}
Well, the general algorithm to find the height of any binary tree (whether a BST,AVL tree, Red Black,etc) is as follows
For the current node:
if(node is NULL) return -1
else
h1=Height of your left child//A Recursive call
h2=Height of your right child//A Recursive call
Add 1 to max(h1,h2) to account for the current node
return this value to parent.
An illustration to the above algorithm is as follows:
(Image courtesy Wikipedia.org)
This code will return the height of any binary tree, not just a red-black tree. It works recursively.
I found this problem difficult to think about in the past, but if we imagine we have a function which returns the height of a sub-tree, we could easily use that to compute the height of a full tree. We do this by computing the height of each side, taking the max, and adding one.
The height of the tree either goes through the left or right branch, so we can take the max of those. Then we add 1 for the root.
Handle the base case of no tree (-1), and we're done.
This is a basic recursion algorithm.
Start at the base case, if the root itself is null the height of tree is -1 as the tree does not exist.
Now imagine at any node what will be the height of the tree if this node were its root?
It would be simply the maximum of the height of left subtree or the right subtree (since you are trying to find the maximum possible height, so you have to take the greater of the 2) and add a 1 to it to incorporate the node itself.
That's it, once you follow this, you're done!
As a recursive function, this computes the height of each child node, using that result to compute the height of the current node by adding + 1 to it. The height of any node is always the maximum height of the two children + 1. A single-node case is probably the easiest to understand, since it has a height of zero (0).
A
Here the call stack looks like this:
height(A) =
max(height(A->left), height(A->right)) + 1
Since both left and right are null, both return (-1), and therefore this reduces to
height(A) = max (-1, -1) + 1;
height(A) = -1 + 1;
height(A) = 0
A slightly more complicated version
A
B C
D E
The recursive calls we care about are:
height(A) =
max(height(B), height(C)) + 1
height(B) =
max(height(D), height(E)) + 1
The single nodes D, E, and C we already know from our first example have a height of zero (they have no children). therefore all of the above reduces to
height(A) = max( (max(0, 0) + 1), 0) + 1
height(A) = max(1, 0) + 1
height(A) = 1 + 1
height(A) = 2
I hope that makes at least a dent in the learning curve for you. Draw them out on paper with some sample trees to understand better if you still have doubts.

Calculating depth of a node of a tree with certain constraints in C++

I have a tree in which there are 3 levels. There is a root node, the root node has 3 leaf nodes and all 3 leaf nodes have 3 other leaf nodes. The nodes represent servers. Now, I have to calculate the depth of a node at for a given level. The depth is calculated as follows:
1) If a server(node) is "up" at any level and any column, then the depth of that node is 0.
2) If a server is in the last level and is "down", then depth of that node is infinity.
3) For all other cases, the depth of the node is the max depth of it's leaf nodes + 1. By max depth, it means the majority value that has occurred in it's child nodes.
A bottom up approach is followed here and hence, the depth of the root node is the depth at level 1. The level is taken as the input parameter in the program. Now, I have to calculate the depth of the root node.
I have made some assumptions regarding the program:
1) To find child nodes, follow the child pointer of the parent node.
2) To find all nodes in a given level, traverse the child nodes from root till I reach that level and make a list of them.
3) Assign the values according to the given constraints.
I am not sure whether my approach is right or not. Please help me guys. Thank you.
I think you want something along the lines of the following pseudocode:
int nodeStatus(const Node& n) {
int status = 0;
if (n.isUp)
return 1;
else if (n.isLeaf)
return -1;
else {
for (Node child : n.children)
status += nodeStatus(child);
}
if (status > 0)
return 1;
else
return -1;
}
This is a recursive method. It first checks if the node is up, in which case it returns 1. Then if the node is down and is a leaf it returns -1 as this is a failure with no children. Finally, if n is an intermediate node then it recursively calls this method again for all the children, summing the result. The final if statement then tests whether the majority of the children are classed as 1 or -1 and returns the value accordingly. Notice that by using the values 1 and -1 it's possible to just sum the children up and providing each node definitely has 3 (or an odd number of) nodes then there will never be a situation where status == 0 which would be the case where there is no majority case.
You will need to define a struct called Node somewhere that looks like this:
struct Node {
Node(bool isUp, bool isLeaf);
bool isUp;
bool isLeaf;
std::Vector<Node> children = new std::Vector<Node>(3);
}
I hope this answers your question, but it may be that I've interpreted it wrong.

Binary tree where value of each node holds the sum of child nodes

This question was asked of me in an interview. How can we convert a BT such that every node in it has a value which is the sum of its child nodes?
Give each node an attached value. When you construct the tree, the value of a leaf is set; construct interior nodes to have the value leaf1.value + leaf2.value.
If you can change the values of the leaf nodes, then the operation has to go "back up" the tree updating the sum values.
This will be a lot easier if you either include back links in the nodes, or implement the tree as a "threaded tree".
Here is a solution that can help you: (the link explains it with tree-diagrams)
Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
/* This function changes a tree to to hold children sum
property */
void convertTree(struct node* node)
{
int left_data = 0, right_data = 0, diff;
/* If tree is empty or it's a leaf node then
return true */
if(node == NULL ||
(node->left == NULL && node->right == NULL))
return;
else
{
/* convert left and right subtrees */
convertTree(node->left);
convertTree(node->right);
/* If left child is not present ten 0 is used
as data of left child */
if(node->left != NULL)
left_data = node->left->data;
/* If right child is not present ten 0 is used
as data of right child */
if(node->right != NULL)
right_data = node->right->data;
/* get the diff of node's data and children sum */
diff = left_data + right_data - node->data;
/* If node's data is smaller then increment node's data
by diff */
if(diff > 0)
node->data = node->data + diff;
/* THIS IS TRICKY --> If node's data is greater then increment left
subtree by diff */
if(diff < 0)
increment(node->left, -diff);
}
}
See the link to see the complete solution and explanation!
Well as Charlie pointed out, you can simply store the sum of respective subtree sizes in each inner node, and have leaves supply constant values at construction (or always implicitly use 1, if you're only interested in the number of leaves in a tree).
This is commonly known as an Augmented Search Tree.
What's interesting is that through this kind of augmentation, i.e., storing additional per-node data, you can derive other kinds of aggregate information for items in the tree as well. Any information you can express as a monoid you can store in an augmented tree, and for this, you'll need to specify:
the data type M; in your example, integers
a binary operation "op" to combine elements, with M op M -> M; in your example, the common "plus" operator
So besides subtree sizes, you can also express stuff like:
priorities (by way of the "min" or "max" operators), for efficient queries on min/max priorities;
rightmost elements in a subtree (i.e., an "op" operator that simply returns its second argument), provided that the elements you store in a tree are ordered somehow. Note that this allows us to view even regular search trees (aka. dictionaries -- "store this, retrieve that key") as augmented trees with a corresponding monoid.
(This concept is rather reminiscent of heaps, or more explicitly treaps, which store random priorities with inner nodes for probabilistic balancing. It's also quite commonly described in the context of Finger Trees, although these are not the same thing.)
If you also provide a neutral element for your monoid, you can then walk down such a monoid-augmented search tree to retrieve specific elements (e.g., "find me the 5th leaf" for your size example; "give me the leaf with the highest priority").
Uhm, anyways. Might have gotten carried away a bit there.. I just happen to find that topic quite interesting. :)
Here is the code for the sum problem. It works i have tested it.
int sum_of_left_n_right_nodes_4m_root(tree* local_tree){
int left_sum = 0;
int right_sum = 0;
if(NULL ==local_tree){
return 0;
}
if((NULL == local_tree->left)&&(NULL == local_tree->right)){
return 0;
}
sum_of_left_n_right_nodes(local_tree->left);
sum_of_left_n_right_nodes(local_tree->right);
if(NULL != local_tree->left)
left_sum = local_tree->left->data +
local_tree->left->sum;
if(NULL != local_tree->right)
right_sum = local_tree->right->data + \
local_tree->right->sum;
local_tree->sum= right_sum + left_sum;
}
With a recursive function you can do so by making the value of each node equal to the sum of the values of it's childs under condition that it has two children, or the value of it's single child if it has one child, and if it has no childs (leaf), then this is the breaking condition, the value never changes.