501 Find Mode in Binary Search Tree 二叉搜索樹中的眾數(shù)
Description:
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.
Example:
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).
題目描述:
給定一個(gè)有相同值的二叉搜索樹(BST),找出 BST 中的所有眾數(shù)(出現(xiàn)頻率最高的元素)蝗拿。
假定 BST 有如下定義:
結(jié)點(diǎn)左子樹中所含結(jié)點(diǎn)的值小于等于當(dāng)前結(jié)點(diǎn)的值
結(jié)點(diǎn)右子樹中所含結(jié)點(diǎn)的值大于等于當(dāng)前結(jié)點(diǎn)的值
左子樹和右子樹都是二叉搜索樹
示例:
例如:
給定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:
如果眾數(shù)超過1個(gè)即舌,不需考慮輸出順序
進(jìn)階:
你可以不使用額外的空間嗎结洼?(假設(shè)由遞歸產(chǎn)生的隱式調(diào)用棧的開銷不被計(jì)算在內(nèi))
思路:
二叉搜索樹的中序遍歷可以返回一個(gè)升序的數(shù)組
- 中序遍歷時(shí), 對(duì)該數(shù)進(jìn)行數(shù)量判斷, 滿足眾數(shù)條件的就加入(進(jìn)階, 不考慮棧的額外開銷)
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1) - 中序遍歷的結(jié)果存儲(chǔ)在數(shù)組中, 再判斷眾數(shù)
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(n)
代碼:
C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
private:
void in_order(TreeNode* root, TreeNode*& pre, int& cur_count, int& max_count, vector<int>& result)
{
if (!root) return;
in_order(root -> left, pre, cur_count, max_count, result);
if (pre) cur_count = (root -> val == pre -> val) ? cur_count + 1 : 1;
if (cur_count == max_count) result.push_back(root -> val);
else if (cur_count > max_count)
{
result.clear();
result.push_back(root -> val);
max_count = cur_count;
}
pre = root;
in_order(root -> right, pre, cur_count, max_count, result);
}
public:
vector<int> findMode(TreeNode* root)
{
vector<int> result;
if (!root) return result;
TreeNode* pre = NULL;
int cur_count = 1, max_count = 0;
in_order(root, pre, cur_count, max_count, result);
return result;
}
};
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] findMode(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
inOrder(root, map);
int max = 0;
List<Integer> list = new ArrayList<>();
for (Integer value : map.values()) if (max < value) max = value;
for (Integer key : map.keySet()) if (map.get(key) == max) list.add(key);
int result[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) result[i] = list.get(i);
return result;
}
private void inOrder(TreeNode root, Map<Integer, Integer> map) {
if (root == null) return;
inOrder(root.left, map);
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
inOrder(root.right, map);
}
}
Python:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import Counter
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
result = []
if not root:
return result
self.in_order(root, result)
dic = Counter(result)
max = 0
for k in dic:
if dic[k] > max:
max = dic[k]
result = []
for k in dic:
if dic[k] == max:
result.append(k)
return result
def in_order(self, root: TreeNode, result: List[int]):
if not root:
return
self.in_order(root.left, result)
result.append(root.val)
self.in_order(root.right, result)