My Algorithm Summary
  • Introduction
  • Data Structure
    • Linked List
    • Stack
      • Monotone Stack
        • 42 Trapping Rain Water
        • 84 Largest Rectangle in Histogram
        • 85 Maximal Rectangle
        • 255 Verify Preorder Sequence in Binary Search Tree
        • 316 Remove Duplicate Characters
        • 402 Remove K Digits
        • 456 132 Pattern
        • 496 Next Greater Element I
        • 503 Next Greater Element II
      • 20 Valid Parentheses
      • 71 Simplify Path
      • 150 Evaluate Reverse Polish Notation
      • 155 Min Stack
      • 173 Binary Search Tree Iterator
      • 224 Basic Calculator
      • 227 Basic Calculator II
      • 232 Implement Queue using Stacks
      • 341 Flatten Nested List Iterator
      • 394 Decode String
      • 439 Ternary Expression Parser
      • 636 Exclusive Time of Functions
    • Heap
    • Trie
    • Segment Tree
    • Tree
      • 94 Binary Tree Inorder Traversal
      • 104 Maximum Depth of Binary Tree
      • 144 Binary Tree Preorder Traversal
      • 145 Binary Tree Postorder Traversal
      • 199 Binary Tree Right Side View
      • 226 Invert Binary Tree
      • 272 Closest Binary Search Tree Value II
      • 508 Most Frequent Subtree Sum
      • 513 Find Bottom Left Tree Value
      • 515 Find Largest Value in Each Tree Row
      • 617 Merge Two Binary Trees
      • 637 Average of Levels in Binary Tree
      • 653 Two Sum IV - Input is a BST
      • 654 Maximum Binary Tree
      • 669 Trim a Binary Search Tree
      • 666 Path Sum IV
      • 230 Kth Smallest Element in a BST
      • 250 Count Univalue Subtrees
      • 538 Convert BST to Greater Tree
      • 404 Sum of Left Leaves
      • 582 Kill Process
      • 112 Path Sum
      • 108 Convert Sorted Array to Binary Search Tree
      • 111 Minimum Depth of Binary Tree
      • 501 Find Mode in Binary Search Tree
      • 102 Binary Tree Level Order Traversal
      • 107 Binary Tree Level Order Traversal II
      • 103 Binary Tree Zigzag Level Order Traversal
      • 113 Path Sum II
      • 437 Path Sum III
      • 99 Recover Binary Search Tree
      • 687 Longest Univalue Path
      • 285 Inorder Successor in BST
      • 101 Symmetric Tree
      • 129 Sum Root to Leaf Numbers
      • 298 Binary Tree Longest Consecutive Sequence
      • 270 Closest Binary Search Tree Value
      • 549 Binary Tree Longest Consecutive Sequence II
      • 98 Validate Binary Search Tree
      • 652 Find Duplicate Subtrees
      • 314 Binary Tree Vertical Order Traversal
      • 333 Largest BST Subtree
      • 563 Binary Tree Tilt
      • 110 Balanced Binary Tree
    • Graph
      • Detect Cycle
  • Algorithms
    • Union Find
      • 695 Max Area of Island
      • 684 Redundant Connection
    • Binary Search
    • Topological Sorting
    • Breadth-First Search
      • 694 Number of Distinct Islands
    • Depth-First Search
    • Two Pointers
    • Sorting
    • Backtacking
    • Dynamic Programming
      • Interval DP
        • Matrix Chain Multiplication
        • Merge Stone
      • KnapSack Problem
        • 0-1 KnapSack
        • Unbounded KnapSack
      • Longest Increasing Subsequence
      • Longest Common Subsequence
    • Reservior Sampling
    • Bipartite Graph
      • Check Bipartite Graph
      • Maximal Matching - Hungarian Algorithm
    • String Pattern Matching
      • KMP Algorithm
      • Rabin Karp Algorithm
  • System Design
    • Consistent Hashing
    • Bloom Filter
    • Caching
      • LRU
      • LFU
    • Mini Twitter
    • Tiny Url
Powered by GitBook
On this page
  • 501. Find Mode in Binary Search Tree
  • 1. Question
  • 2. Implementation
  • 3. Time & Space Complexity

Was this helpful?

  1. Data Structure
  2. Tree

501 Find Mode in Binary Search Tree

Previous111 Minimum Depth of Binary TreeNext102 Binary Tree Level Order Traversal

Last updated 5 years ago

Was this helpful?

501. Find Mode in Binary Search Tree

1. Question

Given a binary search tree (BST) with duplicates, find all the(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).

2. Implementation

(1) BFS + HashMap

class Solution {
    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[0];
        }

        Map<Integer, Integer> map = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int max = 0;

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();

                map.put(curNode.val, map.getOrDefault(curNode.val, 0) + 1);
                max = Math.max(max, map.get(curNode.val));

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
        }

        List<Integer> list = new ArrayList<>();
        for (int key : map.keySet()) {
            if (max == map.get(key)) {
                list.add(key);
            }
        }

        int index = 0;
        int[] res = new int[list.size()];

        for (int e : list) {
            res[index++] = e;
        }
        return res;
    }
}

(2) Inorder Traversal

维护三个变量pre,curMax, max, pre指的是之前遍历到的value,curMax代表当前value的次数,max代表遇到的数中,出现最多的次数。利用Binary Search Tree的特点,对树进行中序遍历。因为是有序的,所以我们可以通过之前遍历到的value和当前的value作比较,如果相同,则curMax加1,否则将它更新为1. 而如果curMax和max相同时,则modes这个数列加上当前的node value,如果curMax > max时,则要更新max的值,并更新modes数列,让它只包含当前的node value。中序遍历结束后,我们要的mode都在modes这个数列里

class Solution {
    public int[] findMode(TreeNode root) {
        int[] pre = new int[1];
        int[] curMax = new int[1];
        int[] max = new int[1];
        List<Integer> modes = new ArrayList<>();

        inorderTraverse(root, pre, curMax, max, modes);

        int[] res = new int[modes.size()];
        for (int i = 0; i < modes.size(); i++) {
            res[i] = modes.get(i);
        }
        return res;
    }

    public void inorderTraverse(TreeNode node, int[] pre, int[] curMax, int[] max, List<Integer> modes) {
        if (node == null) {
            return;
        }

        inorderTraverse(node.left, pre, curMax, max, modes);

        if (node.val == pre[0]) {
            curMax[0] += 1;
        }
        else {
            curMax[0] = 1;
        }

        if (curMax[0] == max[0]) {
            modes.add(node.val);
        }
        else if (curMax[0] > max[0]) {
            max[0] = curMax[0];
            modes.clear();
            modes.add(node.val);
        }

        pre[0] = node.val;

        inorderTraverse(node.right, pre, curMax, max, modes);
    }
}

3. Time & Space Complexity

BFS + HashMap: 时间复杂度:O(n), 空间复杂度: O(n)

Inorder Traversal: 时间复杂度: O(n), 空间复杂度: O(n)

mode(s)