Find mode in Binary Search Tree

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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 = 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的主要内容,如果未能解决你的问题,请参考以下文章

501. Find Mode in Binary Search Tree

501. Find Mode in Binary Search Tree

[LeetCode] Find Mode in Binary Search Tree

501. Find Mode in Binary Search Tree - Easy

leetcode 501. Find Mode in Binary Search Tree

LeetCode_501. Find Mode in Binary Search Tree