REC9 JAVA Programming
public class TreeNode<T> { private T value = null; private TreeNode[] children = newTreeNode[100]; private int childCount = 0;
TreeNode(T value) { this.value = value; } public TreeNode<T> addChild(T value) { TreeNode<T> newChild = newTreeNode<T>(value); children[childCount++] =newChild; return newChild; } // starter method for various traversalprints void traverse(TreeNode<T> startnode ){ if (startnode != null) { for (int i = 0; i< startnode.childCount; i++) { traverse(startnode.children); } } return; }
void printTree(TreeNode<T> obj){ traverse(obj,0); System.out.println(obj.value); }}
REFERENCE CODE 2
import java.util.Arrays;
public class TreeRun {
public static void main(String[]args) { TreeNode<String>menu = new TreeNode("Computer Science"); TreeNode<String> item = menu.addChild("Courses"); item.addChild("Python"); item.addChild("Java"); item.addChild("Data Structure"); item = menu.addChild("Faculty"); item.addChild("Engel"); item.addChild("Korth"); item= item.addChild("Klukowska"); item.addChild("Section1"); item.addChild("Section2"); menu.printTree(menu); }
}
Use the attached code to : 1) Generate a tree where each node has exactly 3 children. It should be of depth 4. The leaf nodes at the last level have no children. Each node's value should be a random number between 1 and 10. 2) Create methods in the TreeNode Class to display the tree in both Pre-Order and Post-Order. 3) Make a method to search the tree for the traversal path with the largest number. A traversal is the root, one of the children, then one of those children, etc...until a leaf node.
REC9 JAVA Programming public class TreeNode { private T value = null; private TreeNode[] children = new TreeNo
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am