family tree is a text file that is read in and converted to a binary tree select
ID: 3704102 • Letter: F
Question
family tree is a text file that is read in and converted to a binary tree
selectIterative Takes a Predicate p and returns the list of all elements
for which p.check is true. The elements must be returned in
"in order" traversal order.
Explanation / Answer
import java.util.Stack;
/* Class to create Node */
class Node {
String name;
Node left, right;
public Node(String data) {
name = data;
left = right = null;
}
// Check method - can be changed to check any variable of node
public void check(String p) {
if (name.contains(p)) {
System.out.print(name + ", ");
}
}
}
// Inorder traversal of tree
class BinaryTree {
Node root;
void selectIterative(String p) {
// Stack holds nodes that are to be visited
Stack<Node> stack = new Stack<Node>();
Node node = root;
// Since in-order, leftmost node will be visited first
while (node != null) {
stack.push(node);
node = node.left;
}
// traverse the tree
while (stack.size() > 0) {
node = stack.pop(); // visit the top node
node.check(p); // call the check method
if (node.right != null) {
node = node.right;
// the next node to be visited is the leftmost
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
}
public static void main(String args[]) {
/* This creates binary tree manually. If you already have the tree
created, pass the root of the tree. */
BinaryTree tree = new BinaryTree();
tree.root = new Node("Emily Adams");
tree.root.left = new Node("Robert Tyler");
tree.root.right = new Node("Jane Tyler");
tree.root.left.left = new Node("Robert Jordan");
tree.root.left.right = new Node("Shawn Jordan");
tree.selectIterative("Robert");
}
}
// OUTPUT - Robert Jordan, Robert Tyler,
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.