How would I implement the preOrder(), given the following class? public class In
ID: 3726438 • Letter: H
Question
How would I implement the preOrder(), given the following class?
public class IntTree {
private class Node {
private int data;
private Node firstChild;
private Node sibling;
private Node parent;
private Node (int d, Node f, Node s, Node p) {
data = d;
firstChild = f;
sibling = s;
parent = p;
}
}
private Node root;
public IntTree(int d) {
//create a one node tree
root = addNode(root, d);
}
private Node addNode(Node currNode, int value) {
//Add a Node to the tree
if(currNode == null) {
return new Node(value, null, null, null);
}
if(value < currNode.data) {
currNode.firstChild = addNode(currNode.firstChild, value);
}
else if(value > currNode.data) {
currNode.sibling = addNode(currNode.sibling, value);
}
return currNode;
}
//Implement PreOrder Method
public String preorder() {
//return a string of the ints in the tree in preorder
//separate the ints with commas
//the implementation must be recursive
}
}
Explanation / Answer
public class IntTree { private class Node { private int data; private Node firstChild; private Node sibling; private Node parent; private Node (int d, Node f, Node s, Node p) { data = d; firstChild = f; sibling = s; parent = p; } } private Node root; public IntTree(int d) { //create a one node tree root = addNode(root, d); } private Node addNode(Node currNode, int value) { //Add a Node to the tree if(currNode == null) { return new Node(value, null, null, null); } if(value currNode.data) { currNode.sibling = addNode(currNode.sibling, value); } return currNode; } //Implement PreOrder Method public String preorder() { //return a string of the ints in the tree in preorder //separate the ints with commas //the implementation must be recursive return preOrderHelper(root); } public String preOrderHelper(Node temp) { if(temp == null) { return ""; } else { String data = temp.data + " "; data += preOrderHelper(temp.firstChild) + " "; data += preOrderHelper(temp.sibling) + " "; return data; } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.