How to take input in Binary Tree in Java
To write a Java program that takes input for trees, you will need to use a data structure that is suitable for representing trees. One common data structure for representing trees is the tree node, which is a data structure that contains a value and pointers to its children.
Here is an example of how you might define a tree node class in Java:
class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
To take input for a tree, you will need to prompt the user to enter the values for each node in the tree. You can then create a new tree node for each value and link the nodes together to form the tree.
Here is an example of how you might write a Java program that takes input for a binary tree (a tree with at most two children per node):
import java.util.Scanner;
class TreeInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Create the root node of the tree
System.out.print("Enter the value for the root node: ");
int rootValue = input.nextInt();
TreeNode root = new TreeNode(rootValue);
// Create the left and right children of the root node
System.out.print("Enter the value for the left child of the root node: ");
int leftValue = input.nextInt();
root.left = new TreeNode(leftValue);
System.out.print("Enter the value for the right child of the root node: ");
int rightValue = input.nextInt();
root.right = new TreeNode(rightValue);
// Continue prompting the user for input until all nodes have been added to the tree
while (true) {
System.out.print("Enter the value for the next node (or 0 to stop): ");
int value = input.nextInt();
if (value == 0) {
break;
}
// Find the correct position for the new node in the tree
TreeNode current = root;
while (true) {
if (value < current.value) {
if (current.left == null) {
current.left = new TreeNode(value);
break;
}
current = current.left;
} else {
if (current.right == null) {
current.right = new TreeNode(value);
break;
}
current = current.right;
}
}
}
// Print the tree
printTree(root);
}
// Print the tree in inorder traversal
public static void printTree(TreeNode node) {
if (node == null) {
return;
}
printTree(node.left);
System.out.println(node.value);
printTree(node.right);
}
}
0 Comments
if you are not getting it then ask i am glad to help