Day 20 - Java

Problem Statement: Lok Sabha Election and Binary Search Tree

In a country, Lok Sabha elections are conducted where different political parties contest in various constituencies. Each constituency has a certain number of voters, and they cast their votes for different political parties. The party with the majority of votes in a constituency wins that constituency.

Your task is to write a program to determine the winner of the Lok Sabha elections based on the votes cast in each constituency.

You are given a binary tree where each node represents a constituency. Each node contains the number of votes for Party A and Party B in that constituency. The tree follows the below format:

Each node has two children, a left child, and a right child.

The left child represents the constituency to the left of the current constituency.

The right child represents the constituency to the right of the current constituency.

For example, consider the following input:

50 30

yes

20 40

yes

10 20

no

no

yes

30 10

no

no

yes

60 20

no

yes

50 70

no

no

The above input represents the following binary tree:

       (50,30)

        /        \

   (20,40)   (60,20)

      /           \          \

(10,20) (30,10)  (50,70)

Write a function String findWinner(TreeNode root) where:

root: A reference to the root node of the binary tree representing the constituencies.

The function should return a string indicating the winner of the Lok Sabha election. If Party A has more total votes across all constituencies, return "Party A wins with x votes." where x is the total votes for Party A. If Party B has more total votes, return "Party B wins with y votes." where y is the total votes for Party B. If both parties have an equal number of votes, return "It's a tie!".

Write a class LokSabhaElection with the following functions:

TreeNode class with attributes votesA and votesB; and also left and right.

left: Reference to the left child node.

right: Reference to the right child node.

TreeNode buildTree should recursively build the binary tree based on the input data. Each node should be created with the number of votes for Party A and Party B, and the presence of left and right children specified by the input.

void calculateTotalVotes(TreeNode root, int[] totalVotes) should calculate the total votes for each party across all constituencies in the binary tree. It should perform a depth-first traversal of the tree and accumulate the votes for Party A and Party B.

String findWinner(TreeNode root) should determine the winner of the Lok Sabha election based on the total votes calculated. It should compare the total votes for Party A and Party B and return a string indicating the winner or a tie.

The main method should call the buildTree function to construct the binary tree. It should then call the findWinner function to determine the winner of the Lok Sabha election based on the binary tree. Finally, it should print the result.

Input Format:

The input consists of a series of lines, each representing a node in the binary tree.

Each line contains:

The number of votes for Party A followed by the number of votes for Party B in the format: votesForPartyA votesForPartyB.

Whether the node has a left child or not. This is indicated by either "yes" or "no".

The input ends when there are no more nodes to input.

Output Format

Return a string indicating the winner of the Lok Sabha election.

Constraints:

1 <= Total number of constituencies <= 10^3

0 <= votesForPartyA, votesForPartyB <= 10^5

The tree is balanced.

Sample Input:

Refer above

Sample Output:

Party A wins with 160 votes.

Explanation:

In the given tree, Party A wins with a total of 220 votes (50 + 20 + 10 + 60 + 30 + 50). Therefore, the output is "Party A wins with 220 votes."

Root Constituency:

Votes for Party A: 50

Votes for Party B: 30

Has a left child (specified by "yes").

Left Child of Root:

Votes for Party A: 20

Votes for Party B: 40

Has a left child (specified by "yes").

Left Child of Left Child of Root:

Votes for Party A: 10

Votes for Party B: 20

Does not have any children (specified by "no" for both left and right children).

Right Child of Left Child of Root:

Votes for Party A: 30

Votes for Party B: 10

Does not have any children (specified by "no" for both left and right children).

Right Child of Root:

Votes for Party A: 60

Votes for Party B: 20

Has a right child (specified by "yes").

Right Child of Right Child of Root:

Votes for Party A: 50

Votes for Party B: 70

Does not have any children (specified by "no" for both left and right children).


SOLUTION:

import java.util.Scanner;


public class LokSabhaElection {

    static class TreeNode {

        int votesA;

        int votesB;

        TreeNode left;

        TreeNode right;


        public TreeNode(int a, int b) {

            votesA = a;

            votesB = b;

            left = null;

            right = null;

        }

    }

    public static TreeNode buildTree(Scanner sc) {

        int vA = sc.nextInt();

        int vB = sc.nextInt();

        TreeNode node = new TreeNode(vA, vB);


        String leftChild = sc.next();

        if (leftChild.equalsIgnoreCase("yes")) {

            node.left = buildTree(sc);

        }

        String rightChild = sc.next();

        if (rightChild.equalsIgnoreCase("yes")) {

            node.right = buildTree(sc);

        }

        return node;

    }


    public static void calculateTotalVotes(TreeNode root, int[] totalVotes) {

        if (root == null) return;

        totalVotes[0] += root.votesA;

        totalVotes[1] += root.votesB;

        calculateTotalVotes(root.left, totalVotes);

        calculateTotalVotes(root.right, totalVotes);

    }


    public static String findWinner(TreeNode root) {

        int[] totalVotes = new int[2];

        calculateTotalVotes(root, totalVotes);

        if (totalVotes[0] > totalVotes[1]) {

            return "Party A wins with " + totalVotes[0] + " votes.";

        } else if (totalVotes[1] > totalVotes[0]) {

            return "Party B wins with " + totalVotes[1] + " votes.";

        } else {

            return "It's a tie!";

        }

    }


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        TreeNode root = buildTree(scanner);

        String winner = findWinner(root);

        System.out.println(winner);

        scanner.close();

    }

}


Insights:

  • The TreeNode class represents each node in the binary tree. It contains attributes votesA and votesB to store the number of votes for Party A and Party B in each constituency. Additionally, it has left and right references to the left and right child nodes, facilitating the construction of the binary tree.
  • The buildTree function constructs the binary tree recursively based on input data. It reads the number of votes for each party in a constituency and determines whether the constituency has left and right child nodes. This recursive approach ensures the entire tree is constructed efficiently.
  • The calculateTotalVotes function performs a depth-first traversal of the binary tree to calculate the total votes for each party. It recursively visits each node, accumulating the votes for Party A and Party B in the totalVotes array.
  • The findWinner function determines the winner of the Lok Sabha election based on the total votes calculated. It compares the total votes for Party A and Party B and returns a string indicating the winner or a tie.
  • Both the tree construction and traversal processes utilize recursion, which is a natural approach for tree-related problems. Recursion simplifies the implementation by breaking down the problem into smaller subproblems, making the code more modular and easier to understand.
  • Each TreeNode instance is initialized with the number of votes for Party A and Party B, along with null references for left and right children. This encapsulation ensures that each node contains all the necessary information for representing a constituency in the Lok Sabha election.
  • The provided code assumes a balanced binary tree structure, where each node has either zero, one, or two children. This balanced structure ensures efficient traversal and calculation of total votes without any bias towards a particular side of the tree.
  • The total votes for each party are calculated efficiently using a depth-first traversal approach. By traversing the entire tree only once, the algorithm computes the total votes with linear time complexity relative to the number of nodes in the tree.
  • The logic for determining the winner is straightforward and based on comparing the total votes for Party A and Party B. It considers three possible outcomes: Party A wins, Party B wins, or it's a tie, providing a clear and concise result based on the calculated votes.
Have you exercised your civic duty by casting your vote for the right party? Remember, your vote today shapes the future of our country, leading towards prosperity and progress!
Jai Hind! 

Comments