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). 见到BST就想到中序遍历。这个题中的BST是可以包含相同的元素的,题目的要求就是找出相同的元素出现次数最多的是哪几个。那么就可以先进行中序遍历得到有序的排列,如果两个相邻的元素相同,那么这个就是连续的,找出连续最多的即可。题目思路就是BST的中序遍历加上最长连续相同子序列。 题目建议不要用附加空间hash等,方法是计算了两次,一次是统计最大的模式出现的次数,第二次的时候构建出来了数组,然后把出现次数等于最大模式次数的数字放到数组的对应位置。
public class Solution { Integer prev = null; int count = 1; int max = 0; public int[] findMode(TreeNode root) { if (root == null) return new int[0]; List<Integer> list = new ArrayList<>(); traverse(root, list); int[] res = new int[list.size()]; for (int i = 0; i < list.size(); ++i) res[i] = list.get(i); return res; } private void traverse(TreeNode root, List<Integer> list) { if (root == null) return; traverse(root.left, list); if (prev != null) { if (root.val == prev) count++; else count = 1; } if (count > max) { max = count; list.clear(); list.add(root.val); } else if (count == max) { list.add(root.val); } prev = root.val; traverse(root.right, list); } }
O(n) time O(n) space public class Solution { Map<Integer, Integer> map; int max = 0; public int[] findMode(TreeNode root) { if(root==null) return new int[0]; this.map = new HashMap<>(); inorder(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 inorder(TreeNode node){ 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); } } Just travel the tree and count, find the those with max counts. Nothing much. Spent 10min on figuring out what is mode.... If using this method (hashmap), inorder/preorder/postorder gives the same result. Because essentially you just travel the entire nodes and count. And BST is not necessary. This method works for any tree.
posted on 2018-11-07 05:08 猪猪🐷 阅读(129) 评论(0) 收藏 举报
浙公网安备 33010602011771号