Skip to content

Latest commit

 

History

History
89 lines (69 loc) · 2.58 KB

501.Find-Mode-in-Binary-Search-Tree.md

File metadata and controls

89 lines (69 loc) · 2.58 KB

Problem on Leetcode

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).

Ideas

Basically, it needs traversing, counting and recording. map can be used to help us to do record and count. For doing that without using any extra space, the property of BST will be used. For each node, the value of the left child is no greater than its value, while the value of right child is no less than the its value. So, when traversing each node, only the value of previous node is required to be compared with the value of current node for counting. As the problem shown, an array of intergers will be returned. While the number of modes is unknown, using ArrayList to store all outputs is a good choice because ArrayList can be converted into array conveniently.

Codes

Supported Language: Java

  • Java Code:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {   
    List<Integer> list = new ArrayList<> ();
    TreeNode preNode = null;
    int max = 0, count = 0;
    
    public int[] findMode(TreeNode root) {
        helper(root);
        int[] res = new int[list.size()];
        for (int i=0; i<res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
    
    private void helper (TreeNode root) {
        if (root == null) return;
        helper(root.left);
        
        if (preNode != null && root.val == preNode.val) {
            count++;
        } else {
            count = 1;
        }
        
        if (count > max) {
            list.clear();
            list.add(root.val);
            max = count;
        } else if (max == count) {
            list.add(root.val);            
        }
        preNode = root;
        helper(root.right);
    }
}