Consider the following java like class definition: Class Node { Node n; void f(i
ID: 3773420 • Letter: C
Question
Consider the following java like class definition:
Class Node {
Node n;
void f(int x) {
Node a = new Node();
a.n = this;
if (x<=2) a.f(x+1);
}
void main() {
Node m = new Node();
m.f(1);
}
}
Trace the function calls beginning with a call to main() and give a picture that illustrates the runtime stack and its ARs at the time the stack has reached its pick size. In each AR for f, include this pointer, the parameter, and the local variable, omitting all else.
Also display all of the object cells and reference pointers that have been created.
Explanation / Answer
import java.util.Queue;
import java.util.LinkedList;
public class TreeTraverse
{
private static class Node<T>
{
public Node<T> left;
public Node<T>right;
public T data;
public Node (T data)
{
this.data=data;
}
public Node <T>getleft()
{
return this.left;
}
public void setleft(Node <T>left)
{
this.left=left;
}
public Node<T>getright()
{
return this.right;
}
public void setright(Node<T>right)
{
this.right=right;
}
}
public static void preorder(Node<?>n)
{
if(n!=null)
{
System.out.println(n.data+" ");
preorder(n.getleft());
preorder(n.getright());
}
}
public static void inorder(Node<?>n)
{
if(n!=null)
{
System.out.println(n.data+" ");
preorder(n.getleft());
preorder(n.getright());
}
}
public static void postorder(Node<?>n)
{
if(n!=null)
{
postorder(n.getleft());
postorder(n.getright());
System.out.println(n.data+" ");
}
}
public static void main(final String[]args)
{
Node<Integer>one=new Node<Integer>(1);
Node<Integer>two=new Node<Integer>(2);
Node<Integer>three=new Node<Integer>(3);
Node<Integer>four=new Node<Integer>(4);
Node<Integer>five=new Node<Integer>(5);
Node<Integer>six=new Node<Integer>(6);
Node<Integer>seven=new Node<Integer>(7);
Node<Integer>eight=new Node<Integer>(8);
Node<Integer>nine=new Node<Integer>(9);
one.setleft(two);
one.setright(three);
two.setleft(four);
two.setright(five);
three.setleft(six);
four.setleft(seven);
six.setleft(eight);
six.setright(nine);
System.out.println("PREORDER IS:");
preorder(one);
System.out.println();
System.out.println("INORDER IS:");
inorder(one);
System.out.println();
System.out.println("POSTORDER IS:");
postorder(one);
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.