Sunday 27 August 2023

Maximum Depth/Height of Binary Tree(code in JAVA)


import java.util.*;

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;
            }
        }
    }
    //levelorder traversal
    public static void levelorder(Node root)
    {
        if(root==null) return;
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        q.add(null);
        while(!q.isEmpty())
        {
            Node currnode = q.remove();
            if(currnode==null) //NULL DENOTES NEW LINE
            {
                System.out.println();
                if(q.isEmpty())
                {
                    break;
                }
                else
                {
                    q.add(null);
                }
            }
            else
            {
                System.out.print(currnode.data+" ");
                if(currnode.left!=null)
                {
                    q.add(currnode.left);
                }
                if(currnode.right!=null)
                {
                    q.add(currnode.right);
                }
            }
        }
    }

    public static ArrayList<Integer> preorderUsingStack(Node root)
    {
        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();
        if (root==null) return preorderArrayList;
        Stack<Node> st = new Stack<Node>();
        st.push(root);
        while(!st.isEmpty())
        {
            root = st.pop();
            preorderArrayList.add(root.data);
            if(root.right != null)
            {
                st.push(root.right);
            }
            if(root.left != null)
            {
                st.push(root.left);
            }

        }
        return preorderArrayList;
    }

    public static ArrayList<Integer> inorderUsingStack(Node root)
    {
        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();
        if (root == null) return null;
        Stack<Node> st = new Stack<Node>();
        Node node = root;
        while(true)
        {
            if(node != null)
            {
                st.push(node);
                node = node.left;
            }
            else
            {
                if(st.isEmpty())
                {
                    break;
                }
                node = st.pop();
                inorderArrayList.add(node.data);
                node = node.right;
            }
        }
        return inorderArrayList;
    }

    public static ArrayList<Integer> postorderUsing2Stack(Node root)
    {
        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();
        if(root == null){return postorderArrayList;}
        Stack<Node> st1 = new Stack<Node>();
        Stack<Node> st2 = new Stack<Node>();
        st1.push(root);
        while(!st1.isEmpty())
        {
            root = st1.pop();
            st2.push(root);
            if(root.left!=null) st1.push(root.left);
            if(root.right!=null) st1.push(root.right);
        }
        while(!st2.isEmpty())
        {
            postorderArrayList.add(st2.pop().data);
        }
        return postorderArrayList;
    }

    public static ArrayList<Integer> postorderUsing1Stack(Node root) {
        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();
        if (root == null) return postorderArrayList;
        Stack<Node> st = new Stack<Node>();
        Node curr = root;
        Node prev = null;
        
        while (curr != null || !st.isEmpty()) {
            if (curr != null) {
                st.push(curr);
                curr = curr.left;
            } else {
                Node peekNode = st.peek();
                if (peekNode.right == null || peekNode.right == prev) { //peekNode is topNode in stack
                    postorderArrayList.add(peekNode.data);
                    prev = peekNode;
                    st.pop();
                } else {
                    curr = peekNode.right;
                }
            }
        }
        
        return postorderArrayList;
    }

    static class node_numOfTraversal_pair
    {
        Node node;
        int num;
        
        public node_numOfTraversal_pair(Node root, int _num)
        {
            this.num = _num;
            this.node = root;
        }
    }

    public static void preInPost_traversal_in_one(Node root, ArrayList<Integer> preorderArrayList, ArrayList<Integer> inorderArrayList, ArrayList<Integer> postorderArrayList)
    {
        Stack<node_numOfTraversal_pair> st = new Stack<node_numOfTraversal_pair>();
        if(root == null) return;
        // or instead pf above two lines you can directly write as below
        // node_numOfTraversal_pair pair = new node_numOfTraversal_pair(root,1);
        // st.push(pair);
        st.push(new node_numOfTraversal_pair(root, 1));
        while(!st.isEmpty())
        {
            node_numOfTraversal_pair it = st.pop();
            // this is part of pre
            // increment 1 to 2 
            // push the left side of the tree
            if(it.num == 1)
            {
                preorderArrayList.add(it.node.data);
                it.num++;
                st.push(it);
                if(it.node.left != null)
                {
                    st.push(new node_numOfTraversal_pair(it.node.left, 1));

                }
            }
            // this is a part of in 
            // increment 2 to 3 
            // push right
            else if(it.num == 2)
            {
                inorderArrayList.add(it.node.data);
                it.num++;
                st.push(it);
                if(it.node.right != null)
                {
                    st.push(new node_numOfTraversal_pair(it.node.right, 1));
                }
            }
            // don't push it back again 
            else    
            {
                postorderArrayList.add(it.node.data);
            }
        }

    }

    public static int maxDepthOfBinaryTree(Node root)
    {
        if(root == null) return 0;

        int leftHeight = maxDepthOfBinaryTree(root.left);
        int rightHeight = maxDepthOfBinaryTree(root.right);
        return 1 + Math.max(leftHeight,rightHeight);
    }

    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.");
        levelorder(root);
        System.out.println(preorderUsingStack(root));
        System.out.println(inorderUsingStack(root));
        System.out.println(postorderUsing2Stack(root));
        System.out.println(postorderUsing1Stack(root));
        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();
        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();
        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();
        preInPost_traversal_in_one(root, preorderArrayList, inorderArrayList, postorderArrayList);
        System.out.print("The preorder traversal is: ");
        for (Integer pre : preorderArrayList) {
            System.out.print(pre+" ");
        }
        System.out.println();
        System.out.print("The inorder traversal is: ");
        for (Integer in : inorderArrayList) {
            System.out.print(in+" ");
        }
        System.out.println();
        System.out.print("The postorder traversal is: ");
        for (Integer post : postorderArrayList) {
            System.out.print(post+" ");
        }
        System.out.println();
        System.out.println("The depth of your tree is: "+maxDepthOfBinaryTree(root));
        scanner.close();
    }
}


  

Preorder, Inorder and Postorder traversals in Binary Tree in one Traversal(Code in JAVA)


import java.util.*;


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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null) //NULL DENOTES NEW LINE

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    public static ArrayList<Integer> preorderUsingStack(Node root)

    {

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        if (root==null) return preorderArrayList;

        Stack<Node> st = new Stack<Node>();

        st.push(root);

        while(!st.isEmpty())

        {

            root = st.pop();

            preorderArrayList.add(root.data);

            if(root.right != null)

            {

                st.push(root.right);

            }

            if(root.left != null)

            {

                st.push(root.left);

            }


        }

        return preorderArrayList;

    }


    public static ArrayList<Integer> inorderUsingStack(Node root)

    {

        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();

        if (root == null) return null;

        Stack<Node> st = new Stack<Node>();

        Node node = root;

        while(true)

        {

            if(node != null)

            {

                st.push(node);

                node = node.left;

            }

            else

            {

                if(st.isEmpty())

                {

                    break;

                }

                node = st.pop();

                inorderArrayList.add(node.data);

                node = node.right;

            }

        }

        return inorderArrayList;

    }


    public static ArrayList<Integer> postorderUsing2Stack(Node root)

    {

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        if(root == null){return postorderArrayList;}

        Stack<Node> st1 = new Stack<Node>();

        Stack<Node> st2 = new Stack<Node>();

        st1.push(root);

        while(!st1.isEmpty())

        {

            root = st1.pop();

            st2.push(root);

            if(root.left!=null) st1.push(root.left);

            if(root.right!=null) st1.push(root.right);

        }

        while(!st2.isEmpty())

        {

            postorderArrayList.add(st2.pop().data);

        }

        return postorderArrayList;

    }


    public static ArrayList<Integer> postorderUsing1Stack(Node root) {

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        if (root == null) return postorderArrayList;

        Stack<Node> st = new Stack<Node>();

        Node curr = root;

        Node prev = null;

        

        while (curr != null || !st.isEmpty()) {

            if (curr != null) {

                st.push(curr);

                curr = curr.left;

            } else {

                Node peekNode = st.peek();

                if (peekNode.right == null || peekNode.right == prev) { //peekNode is topNode in stack

                    postorderArrayList.add(peekNode.data);

                    prev = peekNode;

                    st.pop();

                } else {

                    curr = peekNode.right;

                }

            }

        }

        

        return postorderArrayList;

    }


    static class node_numOfTraversal_pair

    {

        Node node;

        int num;

        

        public node_numOfTraversal_pair(Node root, int _num)

        {

            this.num = _num;

            this.node = root;

        }

    }


    public static void preInPost_traversal_in_one(Node root, ArrayList<Integer> preorderArrayList, ArrayList<Integer> inorderArrayList, ArrayList<Integer> postorderArrayList)

    {

        Stack<node_numOfTraversal_pair> st = new Stack<node_numOfTraversal_pair>();

        if(root == null) return;

        // or instead pf above two lines you can directly write as below

        // node_numOfTraversal_pair pair = new node_numOfTraversal_pair(root,1);

        // st.push(pair);

        st.push(new node_numOfTraversal_pair(root, 1));

        while(!st.isEmpty())

        {

            node_numOfTraversal_pair it = st.pop();

            // this is part of pre

            // increment 1 to 2 

            // push the left side of the tree

            if(it.num == 1)

            {

                preorderArrayList.add(it.node.data);

                it.num++;

                st.push(it);

                if(it.node.left != null)

                {

                    st.push(new node_numOfTraversal_pair(it.node.left, 1));


                }

            }

            // this is a part of in 

            // increment 2 to 3 

            // push right

            else if(it.num == 2)

            {

                inorderArrayList.add(it.node.data);

                it.num++;

                st.push(it);

                if(it.node.right != null)

                {

                    st.push(new node_numOfTraversal_pair(it.node.right, 1));

                }

            }

            // don't push it back again 

            else    

            {

                postorderArrayList.add(it.node.data);

            }

        }


    }


    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.");

        levelorder(root);

        System.out.println(preorderUsingStack(root));

        System.out.println(inorderUsingStack(root));

        System.out.println(postorderUsing2Stack(root));

        System.out.println(postorderUsing1Stack(root));

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        preInPost_traversal_in_one(root, preorderArrayList, inorderArrayList, postorderArrayList);

        System.out.print("The preorder traversal is: ");

        for (Integer pre : preorderArrayList) {

            System.out.print(pre+" ");

        }

        System.out.println();

        System.out.print("The inorder traversal is: ");

        for (Integer in : inorderArrayList) {

            System.out.print(in+" ");

        }

        System.out.println();

        System.out.print("The postorder traversal is: ");

        for (Integer post : postorderArrayList) {

            System.out.print(post+" ");

        }

        scanner.close();

    }

}



  

PostOrder Traversal in Binary Tree using 1 stack(Code in JAVA)

I recommend you to watch this youtube video before seeing the  code for algorithmic intution

Link--> Fit Coder YouTube link

import java.util.*;


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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null) //NULL DENOTES NEW LINE

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    public static ArrayList<Integer> preorderUsingStack(Node root)

    {

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        if (root==null) return preorderArrayList;

        Stack<Node> st = new Stack<Node>();

        st.push(root);

        while(!st.isEmpty())

        {

            root = st.pop();

            preorderArrayList.add(root.data);

            if(root.right != null)

            {

                st.push(root.right);

            }

            if(root.left != null)

            {

                st.push(root.left);

            }


        }

        return preorderArrayList;

    }


    public static ArrayList<Integer> inorderUsingStack(Node root)

    {

        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();

        if (root == null) return null;

        Stack<Node> st = new Stack<Node>();

        Node node = root;

        while(true)

        {

            if(node != null)

            {

                st.push(node);

                node = node.left;

            }

            else

            {

                if(st.isEmpty())

                {

                    break;

                }

                node = st.pop();

                inorderArrayList.add(node.data);

                node = node.right;

            }

        }

        return inorderArrayList;

    }


    public static ArrayList<Integer> postorderUsing2Stack(Node root)

    {

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        if(root == null){return postorderArrayList;}

        Stack<Node> st1 = new Stack<Node>();

        Stack<Node> st2 = new Stack<Node>();

        st1.push(root);

        while(!st1.isEmpty())

        {

            root = st1.pop();

            st2.push(root);

            if(root.left!=null) st1.push(root.left);

            if(root.right!=null) st1.push(root.right);

        }

        while(!st2.isEmpty())

        {

            postorderArrayList.add(st2.pop().data);

        }

        return postorderArrayList;

    }


    public static ArrayList<Integer> postorderUsing1Stack(Node root) {

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        if (root == null) return postorderArrayList;

        

        Stack<Node> st = new Stack<Node>();

        Node curr = root;

        Node prev = null;

        

        while (curr != null || !st.isEmpty()) {

            if (curr != null) {

                st.push(curr);

                curr = curr.left;

            } else {

                Node peekNode = st.peek();

                if (peekNode.right == null || peekNode.right == prev) { //peekNode is topNode in stack

                    postorderArrayList.add(peekNode.data);

                    prev = peekNode;

                    st.pop();

                } else {

                    curr = peekNode.right;

                }

            }

        }

        

        return postorderArrayList;

    }


    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.");

        levelorder(root);

        System.out.println(preorderUsingStack(root));

        System.out.println(inorderUsingStack(root));

        System.out.println(postorderUsing2Stack(root));

        System.out.println(postorderUsing1Stack(root));

        scanner.close();

    }

}



  

Saturday 26 August 2023

Codeforces : 

Problem Statement Link -->   Problem - A - Codeforces

Before seeing the code, I suggest you to watch this youtube video to get the Math behind it. 

YouTube Video By cpwithcpp youtube channel

Solution in JAVA:


import java.util.Scanner;

import java.util.ArrayList;


public class test1 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int t = scanner.nextInt();

        

        while (t-- > 0) {

            int x = scanner.nextInt();

            int y = scanner.nextInt();

            int n = scanner.nextInt();

            

            ArrayList<Integer> vec = new ArrayList<>();

            

            int c = 1;

            vec.add(y);

            

            for (int i = 1; i < n; i++) {

                vec.add(vec.get(i - 1) - c);

                c++;

            }

            

            if (vec.get(n - 1) >= x) {

                vec.set(n - 1, x);

                

                for (int i = n - 1; i >= 0; i--) {

                    System.out.print(vec.get(i) + " ");

                }

                System.out.println();

                continue;

            }

            

            System.out.println("-1");

        }

        scanner.close();

    }

}


PostOrder Traversal in BinaryTree using 2 Stacks(Code in JAVA)


import java.util.*;


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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null) //NULL DENOTES NEW LINE

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    public static ArrayList<Integer> preorderUsingStack(Node root)

    {

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        if (root==null) return preorderArrayList;

        Stack<Node> st = new Stack<Node>();

        st.push(root);

        while(!st.isEmpty())

        {

            root = st.pop();

            preorderArrayList.add(root.data);

            if(root.right != null)

            {

                st.push(root.right);

            }

            if(root.left != null)

            {

                st.push(root.left);

            }


        }

        return preorderArrayList;

    }


    public static ArrayList<Integer> inorderUsingStack(Node root)

    {

        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();

        if (root == null) return null;

        Stack<Node> st = new Stack<Node>();

        Node node = root;

        while(true)

        {

            if(node != null)

            {

                st.push(node);

                node = node.left;

            }

            else

            {

                if(st.isEmpty())

                {

                    break;

                }

                node = st.pop();

                inorderArrayList.add(node.data);

                node = node.right;

            }

        }

        return inorderArrayList;

    }


    public static ArrayList<Integer> postorderUsing2Stack(Node root)

    {

        ArrayList<Integer> postorderArrayList = new ArrayList<Integer>();

        if(root == null){return postorderArrayList;}

        Stack<Node> st1 = new Stack<Node>();

        Stack<Node> st2 = new Stack<Node>();

        st1.push(root);

        while(!st1.isEmpty())

        {

            root = st1.pop();

            st2.push(root);

            if(root.left!=null) st1.push(root.left);

            if(root.right!=null) st1.push(root.right);

        }

        while(!st2.isEmpty())

        {

            postorderArrayList.add(st2.pop().data);

        }

        return postorderArrayList;

    }


    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.");

        levelorder(root);

        System.out.println(preorderUsingStack(root));

        System.out.println(inorderUsingStack(root));

        System.out.println(postorderUsing2Stack(root));

        scanner.close();

    }

}



  

InOrder Traversal in BinaryTree using iterative method and Stack(Code in Java)


import java.util.*;


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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null) //NULL DENOTES NEW LINE

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    public static ArrayList<Integer> preorderUsingStack(Node root)

    {

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        if (root==null) return preorderArrayList;

        Stack<Node> st = new Stack<Node>();

        st.push(root);

        while(!st.isEmpty())

        {

            root = st.pop();

            preorderArrayList.add(root.data);

            if(root.right != null)

            {

                st.push(root.right);

            }

            if(root.left != null)

            {

                st.push(root.left);

            }


        }

        return preorderArrayList;

    }


    public static ArrayList<Integer> inorderUsingStack(Node root)

    {

        ArrayList<Integer> inorderArrayList = new ArrayList<Integer>();

        if (root == null) return null;

        Stack<Node> st = new Stack<Node>();

        Node node = root;

        while(true)

        {

            if(node != null)

            {

                st.push(node);

                node = node.left;

            }

            else

            {

                if(st.isEmpty())

                {

                    break;

                }

                node = st.pop();

                inorderArrayList.add(node.data);

                node = node.right;

            }

        }

        return inorderArrayList;

    }


    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.");

        levelorder(root);

        System.out.println(preorderUsingStack(root));

        System.out.println(inorderUsingStack(root));

        scanner.close();

    }

}



  



PreOrder Traversal using iterative approarch(Code in JAVA)


import java.util.*;


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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null) //NULL DENOTES NEW LINE

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    public static ArrayList<Integer> preorderUsingStack(Node root)

    {

        ArrayList<Integer> preorderArrayList = new ArrayList<Integer>();

        if (root==null) return preorderArrayList;

        Stack<Node> st = new Stack<Node>();

        st.push(root);

        while(!st.isEmpty())

        {

            root = st.pop();

            preorderArrayList.add(root.data);

            if(root.right != null)

            {

                st.push(root.right);

            }

            if(root.left != null)

            {

                st.push(root.left);

            }


        }

        return preorderArrayList;

    }


    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.");

        levelorder(root);

        System.out.println(preorderUsingStack(root));

        scanner.close();

    }

}



  

Friday 25 August 2023

LevelOrder Traversal in Binary Tree (code in JAVA)



import java.util.LinkedList;

import java.util.Queue;

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;

            }

        }

    }

    //levelorder traversal

    public static void levelorder(Node root)

    {

        if(root==null) return;

        Queue<Node> q = new LinkedList<>();

        q.add(root);

        q.add(null);

        while(!q.isEmpty())

        {

            Node currnode = q.remove();

            if(currnode==null)

            {

                System.out.println();

                if(q.isEmpty())

                {

                    break;

                }

                else

                {

                    q.add(null);

                }

            }

            else

            {

                System.out.print(currnode.data+" ");

                if(currnode.left!=null)

                {

                    q.add(currnode.left);

                }

                if(currnode.right!=null)

                {

                    q.add(currnode.right);

                }

            }

        }

    }


    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.");

        levelorder(root);

        scanner.close();

    }

}



  

 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();
    }
}


  

 BinaryTree Data Structure implementation in JAVA: (Hard Coding Method)


public class test {

    static class Node {   

        int data;

        Node left;

        Node right;


        public Node(int data) {

            this.data = data;

            this.left = null;  // even if we do not explicitly specify them as null  then also it is by default                                            //set up as null in JAVA but it is always a good practise to assign them as          this.right = null;                                    //null

         

        }

    }

 

    static class BinaryTree {

        static Node buildTree(int rootValue) {

            if (rootValue == -1) return null;

            Node newNode = new Node(rootValue); // Now you can instantiate Node directly

            //newNode.left = null;

            //newNode.right = null;

            return newNode;

        }

    }


    public static void main(String[] args) {

        // You can create instances of Node and BinaryTree here as needed

        BinaryTree bt = new BinaryTree();

//For the sake of understanding we are doing hardcoding now. We'll see user input coding also in next article

        Node root = BinaryTree.buildTree(10); //Node root = bt.buildTree(10);

        root.left = new Node(6); 

        root.right= new Node(12);

        root.left.left = new Node(5);

        root.right.right = new Node(7);

        System.out.println(root.data);

        System.out.println(root.left.data+" "+root.right.data);

        System.out.println(root.left.left.data+" "+root.right.right.data);

         /* Our Tree is something like below:

                10
                /\

            6       12

            /            \

        5                    7

*/

    }

}

/*

Question: when we are removing both newnode.right and newnode.left = null and also this,left=null and this.right=null then also we are getting root.left value as null and no error is coming why?

The reason you're not seeing any errors or changes in the behavior of your program when you remove both newnode.left = null; and newnode.right = null; from the buildTree method and also remove this.left = null; and this.right = null; from the Node constructor is because Java automatically initializes object fields to default values when an object is created.

In Java, when you create a new object (instance of a class), all instance variables (fields) are automatically initialized to default values. For numeric types like int, the default value is 0, and for object types, including reference types like Node, the default value is null.

In your Node class constructor, you are manually setting left and right to null, but if you don't provide any initialization for these fields, Java will still initialize them to null by default when you create a new Node object.

Similarly, in the buildTree method, even if you remove the lines that explicitly set newnode.left and newnode.right to null, Java will automatically set them to null when the Node object is created.

That's why you're not observing any difference in behavior or errors when you remove these lines. Java's default behavior takes care of it for you.

 */

Thursday 24 August 2023

 Codeforces Round 894 Div 3 Solution:

Problem Statement Link -->   Problem - A - Codeforces

Solution in JAVA:


import java.util.*;


public class test {


    public static void main(String[] args) {


        Scanner scanner = new Scanner(System.in);


        int testCases = scanner.nextInt();


        for (int testCase = 0; testCase < testCases; testCase++) {


            int numRows = scanner.nextInt();

            int numCols = scanner.nextInt();


            List<String> carpetRows = new ArrayList<>();


            for (int i = 0; i < numRows; i++) {

                carpetRows.add(scanner.next());

            }


            int requiredColumns = 4;

            String target = "vika";

            int targetIndex = 0;

            int selectedColumns = 0;


            for (int col = 0; col < numCols; col++) {


                boolean foundColumn = false;


                for (int row = 0; row < numRows; row++) {


                    String rowContent = carpetRows.get(row);

                    char currentChar = rowContent.charAt(col);


                    if (currentChar == target.charAt(targetIndex)) {

                        targetIndex++;

                        foundColumn = true;

                        break;

                    }

                }


                if (foundColumn) {

                    selectedColumns++;

                    if (selectedColumns == requiredColumns) {

                        break;

                    }

                }

            }


            if (selectedColumns == requiredColumns) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }


        scanner.close();

    }

}


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...