Leetcode 501 Find Mode in Binary Search Tree
阿新 • • 發佈:2019-01-28
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
- 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.
問題不復雜,就是一個遍歷加map的問題
基本做法如下
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int max = 0; public int[] findMode(TreeNode root) { if(root == null){ return new int[0]; } Map<Integer, Integer> map = new HashMap<>(); helper(map, root); List<Integer> list = new LinkedList<>(); for(int key: map.keySet()){ if(map.get(key) == max) list.add(key); } int[] res = new int[list.size()]; for(int i = 0; i<res.length; i++) res[i] = list.get(i); return res; } private void helper(Map<Integer, Integer> map, TreeNode root){ if(root == null){ return; } if(map.containsKey(root.val)){ map.put(root.val, map.get(root.val) + 1); }else{ map.put(root.val, 1); } max = Math.max(max, map.get(root.val)); helper(map, root.right); helper(map, root.left); } }
當然,我寫完之後,發現大大的做法還是讓人跪服 O(1)的space啊