Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class Tree {
- Node root;
- static class Node {
- int value;
- Node left, right;
- Node(int value) {
- this.value = value;
- this.left = null;
- this.right = null;
- }
- }
- public void inOrder(Node root) {
- if (root != null) {
- inOrder(root.left);
- System.out.print(root.value + " ");
- inOrder(root.right);
- }
- }
- void preOrder(Node root) {
- if (root != null) {
- System.out.print(root.value + " ");
- preOrder(root.left);
- preOrder(root.right);
- }
- }
- void postOrder(Node root) {
- if (root != null) {
- postOrder(root.left);
- postOrder(root.right);
- System.out.print(root.value + " ");
- }
- }
- public Node insertLevelOrder(int[] arr, Node root, int i) {
- if (i < arr.length) {
- Node temp = new Node(arr[i]);
- root = temp;
- root.left = insertLevelOrder(arr, root.left,
- 2 * i + 1);
- root.right = insertLevelOrder(arr, root.right,
- 2 * i + 2);
- }
- return root;
- }
- public static void main(String[] args) {
- Tree binaryTree = new Tree();
- Scanner scan = new Scanner(System.in);
- ArrayList<Integer> input = new ArrayList<>();
- System.out.println("Enter integers [n to stop]");
- int counter = 1;
- do {
- try {
- System.out.print(counter + ". >> ");
- input.add(scan.nextInt());
- counter++;
- } catch (InputMismatchException exception) {
- break;
- }
- } while (true);
- binaryTree.root = binaryTree.insertLevelOrder(input.stream().mapToInt(Integer::intValue).toArray(), binaryTree.root, 0);
- System.out.print("Full binary tree: ");
- for (int num : input) {
- System.out.print(num + " ");
- }
- System.out.print("\nInOrder Traversal: ");
- binaryTree.inOrder(binaryTree.root);
- System.out.print("\nPreOrder Traversal: ");
- binaryTree.preOrder(binaryTree.root);
- System.out.print("\nPostOrder Traversal: ");
- binaryTree.postOrder(binaryTree.root);
- }
- }
Add Comment
Please, Sign In to add comment