501. Find Mode in Binary Search Tree 找二叉搜索树的众数

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
    
     2
    /
   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. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int[] FindMode(TreeNode root) {
  12. List<int> modes = new List<int>();
  13. int modeCount = 0, lastValue = int.MinValue, lastValueCount = 0;
  14. Stack<TreeNode> stack = new Stack<TreeNode>();
  15. TreeNode current = root;
  16. while (current != null) {
  17. stack.Push(current);
  18. current = current.left;
  19. }
  20. while (stack.Count != 0) {
  21. current = stack.Pop();
  22. if (current.val == lastValue) {
  23. lastValueCount++;
  24. } else {
  25. lastValue = current.val;
  26. lastValueCount = 1;
  27. }
  28. if (lastValueCount > modeCount) {
  29. modes.Clear();
  30. modes.Add(current.val);
  31. modeCount = lastValueCount;
  32. } else if (lastValueCount == modeCount) {
  33. modes.Add(current.val);
  34. }
  35. TreeNode node = current.right;
  36. while (node != null) {
  37. stack.Push(node);
  38. node = node.left;
  39. }
  40. }
  41. return modes.ToArray();
  42. }
  43. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/cfc11b676fdabc12c02882b8e251c80d.html