Java Write a recursive method for the class BinaryTree that

Java

Write a recursive method for the class BinaryTree that counts the number of times an object occurs in a tree. (Note that this method is just for binary trees- not a more specific kind of tree.)

The method header is:

public int count(T anObject)

Hint: write a private helper method: countHelper(BinaryNodeInterface<T> node, object) and review the BinaryTree class to review the instance variables provided. The code in segment 24.10 might be helpful.

Solution

Answer :-

BinaryTree :

import java.util.Stack;
public class Main {
public static void main(String[] args) throws Exception {
BinaryTree bt = BinaryTree.create();
System.out .println(\"printing nodes of binary tree on InOrder using recursion\");
bt.inOrder();
}
}

class BinaryTree {
static class TreeNode {
String data;
TreeNode left, right;
TreeNode(String value) {
this.data = value;
left = right = null;
  
}
  
}

TreeNode root;

public void inOrder() {
inOrder(root);
}
  
private void inOrder(TreeNode node) {
if (node == null) {
return;
}
inOrder(node.left);
System.out.printf(\"%s \", node.data);
inOrder(node.right);
}


public static BinaryTree create() {
BinaryTree tree = new BinaryTree();
TreeNode root = new TreeNode(\"40\");
tree.root = root;
tree.root.left = new TreeNode(\"20\");
tree.root.left.left = new TreeNode(\"10\");
tree.root.left.left.left = new TreeNode(\"5\");
tree.root.left.right = new TreeNode(\"30\");
tree.root.right = new TreeNode(\"50\");
tree.root.right.right = new TreeNode(\"60\");
tree.root.right.right.left = new TreeNode(\"67\");
tree.root.right.right.right = new TreeNode(\"78\");
return tree;
  
}
}

Java Write a recursive method for the class BinaryTree that counts the number of times an object occurs in a tree. (Note that this method is just for binary tre
Java Write a recursive method for the class BinaryTree that counts the number of times an object occurs in a tree. (Note that this method is just for binary tre

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site