This is from another Question i just forgot to Ask for it inJava. Need this conv
ID: 3618248 • Letter: T
Question
This is from another Question i just forgot to Ask for it inJava. Need this converted to Java asap.Will rate lifesaver on first post.
Thanks, Aphareus
Edit: Thought id put in the orginal Question so you havesomeunderstanding:
(Implementing preorder without using recrusion) Implement thepreorder method in Binary Tree using a stack instead ofrecursion.
public String preorder(TreeNode root)
{
String output = "";
Stack<TreeNode> stack = newStack<TreeNode>();
if(root != null)
{
stack.push(root);
}
while(!stack.isEmpty())
{
TreeNodetemp = stack.pop();
output +=temp.getValue();
if(temp.getLeft() != null)
{
stack.push(temp.getLeft());
}
if(temp.getRight() != null)
{
stack.push(temp.getRight());
}
}
return output;
}
Explanation / Answer
publicString preorder(TreeNode root) { String output= ""; Stack stack= newStack(); if(root!= null) { stack.push(root); } while(!stack.isEmpty()) { TreeNode temp =stack.pop(); output+= temp.getValue(); if(temp.getLeft() !=null) { stack.push(temp.getLeft()); } if(temp.getRight() !=null) { stack.push(temp.getRight()); } } returnoutput; } The above is Java code... I used a standard definition for TreeNode: public classTreeNode { privateTreeNode left, right; privateObject value; publicTreeNode(TreeNode left, TreeNode right, Object val) { setLeft(left); setRight(right); setValue(val); } publicTreeNode getLeft() { return left; } publicTreeNode getRight() { return right; } publicObject getValue() { return value; } publicvoid setLeft(TreeNode l) { left = l; } publicvoid setRight(TreeNode r) { right = r; } } Enclose the preorder() method in aclass, and the code should work fine.Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.