501. Find Mode in Binary Search Tree

女爷i 2021-11-29 18:42 320阅读 0赞

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
  • Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

  1. 1
  2. \
  3. 2
  4. /
  5. 2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

  1. private readonly Dictionary<int, int> dictionary = new Dictionary<int, int>();
  2. public int[] FindMode(TreeNode root)
  3. {
  4. Chuck(root);
  5. if (dictionary.Count > 0)
  6. {
  7. int max = dictionary.Max(x => x.Value);
  8. var array = dictionary.Where(x => x.Value == max).Select(x => x.Key).ToArray();
  9. return array;
  10. }
  11. else
  12. {
  13. return new int[0];
  14. }
  15. }
  16. private void Chuck(TreeNode node)
  17. {
  18. if (node == null)
  19. {
  20. return;
  21. }
  22. int val = node.val;
  23. if (dictionary.ContainsKey(val))
  24. {
  25. dictionary[val]++;
  26. }
  27. else
  28. {
  29. dictionary[val] = 1;
  30. }
  31. Chuck(node.left);
  32. Chuck(node.right);
  33. }

Runtime: 272 ms, faster than 32.05% of C# online submissions for Find Mode in Binary Search Tree.

Memory Usage: 33.1 MB, less than 11.30% of C# online submissions forFind Mode in Binary Search Tree.

转载于:https://www.cnblogs.com/chucklu/p/10959760.html

发表评论

表情:
评论列表 (有 0 条评论,320人围观)

还没有评论,来说两句吧...

相关阅读