DEV Community

Cover image for Data Structure in Java: Binary Search Tree
luthfisauqi17
luthfisauqi17

Posted on • Edited on

2 1

Data Structure in Java: Binary Search Tree

public class BinarySearchTree {
    private class Node {
        private int data;
        private Node left, right;

        private Node(int data) {
            this.data = data;
            this.left = this.right = null;
        }
    }

    Node root;

    BinarySearchTree() {
        this.root = null;
    }

    public void insert(int data) {
        this.root = insert(this.root, data);
    }

    private Node insert(Node root, int data) {
        if (root == null) {
            root = new Node(data);
            return root;
        }
        if (data < root.data) root.left = insert(root.left, data);
        else if (data > root.data) root.right = insert(root.right, data);
        return root;
    }

    public void show(String type) {
        switch (type) {
            case "preorder":
                preOrder(this.root);
                break;
            case "inorder":
                inOrder(this.root);
                break;
            case "postorder":
                postOrder(this.root);
                break;
            default:
                System.out.println("Wrong Type (preorder, inorder, postorder)");
        }
    }

    private void preOrder(Node root) {
        if(root != null) {
            System.out.print(root.data + " ");
            inOrder(root.left);
            inOrder(root.right);
        }
    }

    private void inOrder(Node root) {
        if(root != null) {
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    }

    private void postOrder(Node root) {
        if(root != null) {
            inOrder(root.left);
            inOrder(root.right);
            System.out.print(root.data + " ");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sources and Images:

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay