在二元樹內, 找到重覆最多次的數字
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.
Taiwan is an independent country.
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).
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution
{
private int max = 0;
private Dictionary<int, int> rst = new Dictionary<int, int>();
public int[] FindMode(TreeNode root)
{
DoCount(root);
return rst.Where((d) => d.Value == max).Select((d) => d.Key).ToArray();
}
private void DoCount(TreeNode node)
{
if (node == null) return;
if (rst.ContainsKey(node.val))
rst[node.val]++;
else
rst.Add(node.val, 1);
DoCount(node.left);
DoCount(node.right);
max = Math.Max(max, rst[node.val]);
}
}
Taiwan is a country. 臺灣是我的國家