原题链接在这里:https://leetcode.com/problems/find-mode-in-binary-search-tree/#/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.
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).
题解:
两遍Binary Tree Inorder Traversal.
第一遍找出有几个mode. 建立res array, 并保留了mode duplicate次数是多少. 第二遍当duplicate次数是mode 的duplicate次数时就加入res中.
Time Complexity: O(n).
Space: O(n), 每个节点都不同, res的size就是O(n). stack space O(logn). 如果利用Binary Tree Inorder Traversal中的Morris Traversal方法可以不用stack space.
AC Java:
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 int curVal; 12 int curCount; 13 int maxCount; 14 int modeNumber; 15 int [] res; 16 17 public int[] findMode(TreeNode root) { 18 inorderTraversal(root); 19 res = new int[modeNumber]; 20 curCount = 0; 21 modeNumber = 0; 22 inorderTraversal(root); 23 return res; 24 } 25 26 private void inorderTraversal(TreeNode root){ 27 if(root == null){ 28 return; 29 } 30 31 inorderTraversal(root.left); 32 handleCurrentNodeValue(root.val); 33 inorderTraversal(root.right); 34 } 35 36 private void handleCurrentNodeValue(int val){ 37 if(val != curVal){ 38 curVal = val; 39 curCount = 0; 40 } 41 curCount++; 42 43 if(curCount > maxCount){ 44 maxCount = curCount; 45 modeNumber = 1; 46 }else if(curCount == maxCount){ 47 if(res != null){ 48 res[modeNumber] = curVal; 49 } 50 modeNumber++; 51 } 52 } 53 }