ogv

Untitled

ogv
Aug 31st, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. /*
  2. Runtime: 676 ms, faster than 14.39% of C# online submissions for Find Duplicate Subtrees.
  3. Memory Usage: 128.3 MB, less than 100.00% of C# online submissions for Find Duplicate Subtrees.
  4. */
  5. public class Solution {
  6.     private const string NullRepresentation = "[[null]]";
  7.    
  8.     public IList<TreeNode> FindDuplicateSubtrees(TreeNode root) {
  9.         var map = new Dictionary<TreeNode, string>();
  10.        
  11.         if (root != null) {
  12.             dfs(root, map);
  13.         }
  14.        
  15.         return map.GroupBy(kv => kv.Value).Where(g => g.Count() > 1).Select(g => g.First().Key).ToList();
  16.     }
  17.    
  18.     private void dfs(TreeNode root, IDictionary<TreeNode, string> map) {
  19.         var sb = new StringBuilder();
  20.         sb.AppendFormat("{0:x8}", root.val);
  21.        
  22.         if (root.left != null) {
  23.             dfs(root.left, map);
  24.             sb.Append(map[root.left]);
  25.         }
  26.         else {
  27.             sb.Append(NullRepresentation);
  28.         }
  29.        
  30.         if (root.right != null) {
  31.             dfs(root.right, map);
  32.             sb.Append(map[root.right]);
  33.         }
  34.         else {
  35.             sb.Append(NullRepresentation);
  36.         }
  37.                
  38.         map[root] = sb.ToString();
  39.     }  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment