問題:node
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.less
Assume a BST is defined as follows:spa
For example:
Given BST [1,null,2,2]
,code
1 \ 2 / 2
return [2]
.遞歸
Note: If a tree has more than one mode, you can return them in any order.ip
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).ci
解決:element
① 利用一個哈希表來記錄數字和其出現次數之間的映射,而後維護一個變量max來記錄當前最多的次數值,這樣在遍歷完樹以後,根據這個max值就能把對應的元素找出來。使用中序遍歷方式遞歸遍歷該樹(注:使用任何一種遍歷方式均可以 )。時間和空間複雜度都是O(N)。get
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution { // 16ms
private int max = 0;//由於在兩個方法中都使用到了這兩個變量,因此將其聲明在方法外面。
private Map<Integer,Integer> map = new HashMap<>();
public int[] findMode(TreeNode root) {
if (root == null) return new int[0];
List<Integer> list = new ArrayList<>();
inorder(root);
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
if(entry.getValue() == max) list.add(entry.getKey());
}
int[] res = new int[list.size()];
for (int i = 0;i < list.size() ;i ++ ) {
res[i] = list.get(i);
}
return res;
}
public void inorder(TreeNode node){
if(node == null) return;
if(node.left != null)inorder(node.left);
map.put(node.val,map.getOrDefault(node.val,0) + 1);
max = Math.max(max,map.get(node.val));
if(node.right != null)inorder(node.right);
}
}it
② 中序遍歷獲得一個遞增的序列,使用一個計數器count記錄相同的值的個數,max記錄最大個數,pre記錄前一個節點的值用於判斷當前節點與前一個是否相等,從而決定要如何操做count;時間複雜度O(n),空間複雜度O(1)
public class Solution { //5 ms
int pre = Integer.MIN_VALUE;//記錄前一個節點數值,用於比較當前節點與以前的節點是否相等
int count = 0;
int max = 0;
public int[] findMode(TreeNode root) {
List<Integer> list = new ArrayList<>();
inorder(root, list);//中序遍歷
int[] arr = new int[list.size()];
for(int i = 0;i < arr.length;i ++){
arr[i] = list.get(i);
}
return arr;
}
public void inorder(TreeNode root, List<Integer> list){
if(root != null){
inorder(root.left, list);
if(root.val == pre){ count ++; }else{ count = 1; pre = root.val; } if(count > max){ max = count; list.clear(); list.add(root.val); }else if(count == max){ list.add(root.val); } inorder(root.right, list); } } }