Friday, 25 August 2023

 BinaryTree Data Structure implementation in JAVA: ( User Input Method)


import java.util.Scanner;

public class test {
    static class Node {
        int data;
        Node left;
        Node right;

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

    static class BinaryTree {
        static Node buildTree(Scanner scanner, String position, int parentValue) {
            System.out.print("Add " + position + " node for " + parentValue + " (y/n): ");
            String userChoice = scanner.next();

            if (userChoice.equalsIgnoreCase("y")) {
                System.out.print("Enter " + position + " node value: ");
                int nodeValue = scanner.nextInt();
                Node newNode = new Node(nodeValue);

                newNode.left = buildTree(scanner, "left", nodeValue);
                newNode.right = buildTree(scanner, "right", nodeValue);

                return newNode;
            } else {
                return null;
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BinaryTree bt = new BinaryTree();
        
        System.out.print("Enter root node value: ");
        int rootValue = scanner.nextInt();
        Node root = new Node(rootValue);

        root.left = bt.buildTree(scanner, "left", rootValue);
        root.right = bt.buildTree(scanner, "right", rootValue);

        System.out.println("Tree construction complete.");
        scanner.close();
    }
}


  

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...