Need help for three BinaryTree class public class BinaryTree { //Implements a Bi
ID: 3754899 • Letter: N
Question
Need help for three BinaryTree class
public class BinaryTree {
//Implements a Binary Tree of Strings
private class Node {
private Node left;
private String data;
private Node right;
private Node parent; // reference to the parent node
// the parent is null for the root node
private Node(Node L, String d, Node r, Node p) {
left = L;
data = d;
right = r;
parent = p;
}
}
private Node root;
public BinaryTree() {
// create an empty tree
root = null;
}
public BinaryTree(String d) {
// create a tree with a single node
root = new Node(null, d, null, root);
}
public BinaryTree(BinaryTree b1, String d, BinaryTree b2) {
// merge the trees b1 AND b2 with a common root with data d
}
Explanation / Answer
For merging the binary trees, we create a new node with String .d as its data. We make BinaryTree b1 the left sub tree of the given node and BinaryTree b2 the right subtree of the given node.
The code is as follows:
/* Class containing left and right child of current
node and key value*/
public class BinaryTree {
//Implements a Binary Tree of Strings
class Node {
public Node left;
public String data;
public Node right;
public Node parent; // reference to the parent node
// the parent is null for the root node
public Node(Node L, String d, Node r, Node p) {
left = L;
data = d;
right = r;
parent = p;
}
}
private Node root;
public BinaryTree() {
// create an empty tree
root = null;
}
public BinaryTree(String d) {
// create a tree with a single node
root = new Node(null, d, null, root);
}
public BinaryTree(BinaryTree b1, String d, BinaryTree b2) {
// merge the trees b1 AND b2 with a common root with data d
root = new Node(null, d, null, root); //creating new Node
root.left = b1.root;
root.right=b2.root;
b1.root.parent=root;
b2.root.parent=root;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.