/Binary Tree

Binary Tree

Node Class

public class Node {

    private int data;
    private Node leftChild;
    private Node rightChild;

    public Node(int data) {
        this.data = data;
        this.leftChild = null;
        this.rightChild = null;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(Node leftChild) {
        this.leftChild = leftChild;
    }

    public Node getRightChild() {
        return rightChild;
    }

    public void setRightChild(Node rightChild) {
        this.rightChild = rightChild;
    }

    @Override
    public String toString() {
        return "Node{" + "data=" + data + ", leftChild=" + leftChild + ", rightChild=" + rightChild + '}';
    }
}

Binary Tree Example

import java.util.Scanner;

public class BinaryTreeExample {

    public static void main(String args[]) {
        Node root = insert();
        preorder(root);
    }

    public static void preorder(Node root) {
        if (root != null) {
            System.out.print(root.getData() + " ");
            preorder(root.getLeftChild());
            preorder(root.getRightChild());
        }
    }

    private static Node insert() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the Element");
        int x = scanner.nextInt();
        if (x == -1) {
            return null;
        }
        Node node = new Node(x);
        System.out.println("Enter the Left Child");
        node.setLeftChild(insert());
        System.out.println("Enter the Right Child");
        node.setRightChild(insert());
        return node;
    }
}