From eeec2c36cb70a468bbf8258468c22c7dd9d68919 Mon Sep 17 00:00:00 2001 From: Tanmay-312 Date: Sun, 28 Apr 2024 09:18:11 +0530 Subject: [PATCH] Added codes for 28 April --- GeeksForGeeks/April/28-4-24/GFG.java | 85 +++++++++++++++++++++++++++ GeeksForGeeks/April/28-4-24/README.md | 2 + LeetCode/April/28-4-24/README.md | 2 + LeetCode/April/28-4-24/Solution.java | 51 ++++++++++++++++ 4 files changed, 140 insertions(+) create mode 100644 GeeksForGeeks/April/28-4-24/GFG.java create mode 100644 GeeksForGeeks/April/28-4-24/README.md create mode 100644 LeetCode/April/28-4-24/README.md create mode 100644 LeetCode/April/28-4-24/Solution.java diff --git a/GeeksForGeeks/April/28-4-24/GFG.java b/GeeksForGeeks/April/28-4-24/GFG.java new file mode 100644 index 0000000..11bc99a --- /dev/null +++ b/GeeksForGeeks/April/28-4-24/GFG.java @@ -0,0 +1,85 @@ +//{ Driver Code Starts +import java.util.*; +import java.io.*; + +class Node{ + int data; + Node next; + + Node(int x){ + data = x; + next = null; + } + +} +class GFG{ + static void printList(Node node) + { + while (node != null) + { + System.out.print(node.data + " "); + node = node.next; + } + System.out.println(); + } + public static void main(String args[]) throws IOException { + Scanner sc = new Scanner(System.in); + int t = sc.nextInt(); + while(t > 0){ + int n = sc.nextInt(); + Node head = new Node(sc.nextInt()); + Node tail = head; + for(int i=0; i[] tree = new Set[n]; + + Arrays.fill(count, 1); + + for (int i = 0; i < n; ++i) + tree[i] = new HashSet<>(); + + for (int[] edge : edges) + { + int u = edge[0]; + int v = edge[1]; + tree[u].add(v); + tree[v].add(u); + } + + postorder(tree, 0, -1, count, ans); + preorder(tree, 0, -1, count, ans); + return ans; + } + + private void postorder(Set[] tree, int node, int parent, int[] count, int[] ans) + { + for (int child : tree[node]) + { + if (child == parent) + continue; + + postorder(tree, child, node, count, ans); + count[node] += count[child]; + ans[node] += ans[child] + count[child]; + } + } + + private void preorder(Set[] tree, int node, int parent, int[] count, int[] ans) + { + for (int child : tree[node]) + { + if (child == parent) + continue; + + ans[child] = ans[node] - count[child] + (tree.length - count[child]); + preorder(tree, child, node, count, ans); + } + } +}