C# || How To Find Duplicate Subtrees Using C#

The following is a module with functions which demonstrates how to find duplicate subtrees using C#.
1. Find Duplicate Subtrees – Problem Statement
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
2. Find Duplicate Subtrees – Solution
The following is a solution which demonstrates how to find duplicate subtrees.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// ============================================================================ // Author: Kenneth Perkins // Date: Apr 1, 2025 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find duplicate subtrees // ============================================================================ /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public IList<TreeNode> FindDuplicateSubtrees(TreeNode root) { var result = new List<TreeNode>(); Traverse(root, new Dictionary<string, int>(), new Dictionary<int, int>(), result); return result; } public int Traverse(TreeNode node, Dictionary<string, int> tripletToID, Dictionary<int, int> cnt, List<TreeNode> result) { if (node == null) { return 0; } string triplet = Traverse(node.left, tripletToID, cnt, result) + "," + node.val + "," + Traverse(node.right, tripletToID, cnt, result); if (!tripletToID.ContainsKey(triplet)) { tripletToID[triplet] = tripletToID.Count + 1; } int id = tripletToID[triplet]; cnt[id] = cnt.GetValueOrDefault(id, 0) + 1; if (cnt[id] == 2) { result.Add(node); } return id; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
[[2,4],[4]]
[[1]]
[[2,3],[3]]
Leave a Reply