首页 > 代码库 > Find mode in Binary Search Tree
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).
Solution: 题目要求O(1)的空间复杂度,所以我们需要先得到有多少个modes,再申请空间。所产生的stack space不计入空间复杂度,因此可用递归。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 private int currentModes = 0; 12 private int currentValue = http://www.mamicode.com/0; 13 private int currentCount = 0; 14 private int modes[]; 15 private int maxCount = 0; 16 17 public int[] findMode (TreeNode root) { 18 helper(root); 19 modes = new int[currentModes]; 20 currentModes = 0; 21 currentCount = 0; 22 helper(root); 23 return modes; 24 } 25 26 private void helper (TreeNode root) { 27 if (root == null) return; 28 29 helper(root.left); 30 31 if (root.val != currentValue) { 32 currentCount = 1; 33 currentValue =http://www.mamicode.com/ root.val; 34 } else { 35 currentCount++; 36 } 37 38 if (currentCount > maxCount) { 39 maxCount = currentCount; 40 currentModes = 1; 41 } else if (currentCount == maxCount) { 42 if (modes != null) 43 modes[currentModes] = root.val; 44 currentModes++; 45 } 46 47 helper(root.right); 48 } 49 }
Find mode in Binary Search Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。