Question
Am I answering the question correctly? Question: A ternary tree is a tree in which every node can have at most 3 children. So, for
Am I answering the question correctly?
Question:
A ternary tree is a tree in which every node can have at most 3 children. So, for each node, we have 3 references: left child, right child and the middle child. An example ternary tree is depicted above. There are four methods to be implemented, described in the following.
public int size()
returns the size (number of nodes) of the tree. In the depicted example tree, size() returns 10.
public boolean contains(int targetKey)
returns true if a target key exists in the tree, otherwise returns false. In the above example tree, contains(8) returns true but contains(21) returns false.
public void preOrder()
prints the tree using pre-order traversal. Note that pre-order in this case prints the root , then visits left, visits middle child, and finally visits the right child.
public boolean isBinaryTree()
returns true if the tree is a binary tree. Note that, an empty tree is a binary tree. Also, a single node is considered a binary tree. In the above example, isBinaryTree() returns false as some nodes have more than two children.
My answer:
class Node {
Node right, left, middle;
int data;
public Node(int data) {
this.data = data;
}
public int size() {
int count = 0;
while (right != null) {
count+=1;
}
while(left != null) {
count +=1;
}
while(middle != null) {
count+=1;
}
return count;
}
public boolean contains(int targetKey) {
if (targetKey == data) {
return true;
}
else if (right != null) {
right.contains(targetKey);
}
else if (left != null) {
left.contains(targetKey);
}
else if (middle != null) {
middle.contains(targetKey);
}
return false;
}
public void preOrder(Node node) {
if (node == null)
return;
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
public boolean isBinaryTree(Node root) {
if(root.left == null & root.right == null) {
return true;
}
boolean left = isBinaryTree(root.left);
boolean right = isBinaryTree(root.right);
if(root.left == null & root.data
return (left & right);
}
else if(root.right == null & (root.data >= root.left.data)) {
return (left & right);
}
else if((root.left != null & root.right != null) & root.data >= root.left.data & root.data
return (left & right);
}
else return false;
}
3 2 8 6 2 6 0 3Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started