Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can anyone explain the logic for the below code?
int FindMax(BinaryTreeNode root)

{

BinaryTreeNode temp;

int max = INT_MIN;

LLQueue Q = new LLQueue();

Q.enQueue(root);

while(!Q.isEmpty())

{

temp = Q.deQueue();

//largest of the three values

if(max < temp.getData())

max = temp.getData();



if(temp.getLeft())

Q.enQueue(temp.getLeft());



if(temp.getRight())

Q.enQueue(temp.getRight());

}

Q.deleteQueue();

return max;

}
Posted
Comments
Sergey Alexandrovich Kryukov 7-Aug-13 16:49pm    
Why? Not a productive question. Write code which has logic, don't show the code written by who-know-who. Or ask a person who did it.
—SA

Since recursion is actually calling a function from itself - it is just putting stuff in the stack. And you can model a stack with an array or a dynamic structure. So you can transform any recursion into a non-recursive algorithm, where your code is doing the stack's functionality. Here is a good gebneral explanation of such a transformation: How to replace recursive functions using stack and while-loop to avoid the stack-overflow[^].

In your case the stack is represented by a linked list based queue. And the code is simply doing a preorder traversal with this queue:
1) take the current root and put it into the queue
2) as long as there is something in the queue:
3)   take the first element from the queue
4)   check value
5)   put it's left and right descendants into the queue (if they exists)
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Aug-13 16:50pm    
Good explanation, a 5.
—SA
Zoltán Zörgő 7-Aug-13 16:51pm    
Thank you.
Do you have any idea how much work explaining code line by line is?
Every single line needs a paragraph of explanation! For example:
int next = r.Next();

Create a new variable called "next" which can hold a integer value. From the previously declared Random instance "r", call the "Next" method to get a new random number, and assign it to the "next" variable.

Can you imagine how long it would take us to explain even a very short code fragment like your example, line by line?

No. It is not going to happen. If you have a specific problem, then ask a question about it. But think first - would you want to sit down for 45 minutes and type up a line-by-line description for no good reason?
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Aug-13 16:52pm    
Absolutely. No wonder the best answers are sometimes down-voted, like this one. Unpleasant facts supported by strong logic irritate (especially morons). My 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900