Untitled
user_0781376
plain_text
10 days ago
2.4 kB
20
Indexable
package Day3; import java.util.LinkedList; import java.util.Queue; // Node structure representing each garden class Node { int data; Node left, right; // Constructor public Node(int value) { this.data = value; this.left = this.right = null; } } public class ParkManagement { // Function to insert a new garden (node) in the binary tree using level order traversal public static Node insert(Node root, int data) { if (root == null) { return new Node(data); } Queue<Node> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { Node temp = queue.poll(); if (temp.left == null) { temp.left = new Node(data); break; } else { queue.add(temp.left); } if (temp.right == null) { temp.right = new Node(data); break; } else { queue.add(temp.right); } } return root; } // Function to count the number of leaf gardens (leaf nodes) in the binary tree public static int countLeafNodes(Node root) { if (root == null) { return 0; // No leaf nodes in an empty tree } // If a node has no children, it's a leaf node if (root.left == null && root.right == null) { return 1; } // Recursively count leaf nodes in the left and right subtrees return countLeafNodes(root.left) + countLeafNodes(root.right); } public static void main(String[] args) { // Creating the root garden of the park Node root = new Node(1); // Main garden ID 1 // Inserting sub-gardens into the park root = insert(root, 2); // Sub-garden ID 2 root = insert(root, 3); // Sub-garden ID 3 root = insert(root, 4); // Sub-garden ID 4 root = insert(root, 5); // Sub-garden ID 5 root = insert(root, 6); // Sub-garden ID 6 root = insert(root, 7); // Sub-garden ID 7 // Counting the number of leaf gardens in the park System.out.println("The number of leaf gardens in the park is: " + countLeafNodes(root)); } }
Editor is loading...
Leave a Comment