zoukankan      html  css  js  c++  java
  • [LeetCode] 501. 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).

    二叉搜索树中的众数。题意是给一个类似二叉树的树,其中的节点值并不是unique的,可以有相等的,但是总体来讲是遵循左子树 <= 根节点 <= 右子树的。请输出二叉搜索树中的众数,也就是出现次数最多的节点。注意节点个数有可能不止一个。

    涉及到二叉搜索树的题目,十有八九需要利用到中序遍历。这道题也不例外,在中序遍历过程中,你会得到一个升序的数组。但是如何在不用hashmap的情况下统计众数的出现次数呢?我们可以用一个变量maxcount记录到目前为止最大的出现次数。遍历树的时候,如果当前这个节点的出现次数是最大的,就把他加入结果集;如果有多个元素的出现次数都是最大的,则也把他们一一加入结果集。但是当有一个元素的出现次数更大的时候,需要将结果集清空并放入这个当前出现次数最大的元素。注意33行清空list的这个动作的时间复杂度是O(n)。

    时间O(n) - list的清空操作暂时忽略不计,这个操作原则上是O(n)级别的

    空间O(n) - output是个list

    Java实现

     1 class Solution {
     2     Integer prev = null;
     3     int count = 1;
     4     int max = 0;
     5 
     6     public int[] findMode(TreeNode root) {
     7         if (root == null) {
     8             return new int[0];
     9         }
    10         List<Integer> list = new ArrayList<>();
    11         traverse(root, list);
    12         int[] res = new int[list.size()];
    13         for (int i = 0; i < list.size(); i++) {
    14             res[i] = list.get(i);
    15         }
    16         return res;
    17     }
    18 
    19     private void traverse(TreeNode root, List<Integer> list) {
    20         if (root == null) {
    21             return;
    22         }
    23         traverse(root.left, list);
    24         if (prev != null) {
    25             if (root.val == prev) {
    26                 count++;
    27             } else {
    28                 count = 1;
    29             }
    30         }
    31         if (count > max) {
    32             max = count;
    33             list.clear();
    34             list.add(root.val);
    35         } else if (count == max) {
    36             list.add(root.val);
    37         }
    38         prev = root.val;
    39         traverse(root.right, list);
    40     }
    41 }

    LeetCode 题目总结

  • 相关阅读:
    [Windows] 一些简单的CMD命令
    开发过程中用到的触发器
    MyEclipse8.5配置struts等框架
    Java编程中中文乱码问题的研究及解决方案
    开源的SSH框架优缺点分析
    java 合并排序算法、冒泡排序算法、选择排序算法、插入排序算法、快速排序
    html,CSS文字大小单位px、em、pt的关系换算
    HTML常用标签参考学习
    匹配中文字符的正则表达式
    Oracle 取上周一到周末的sql
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13723345.html
Copyright © 2011-2022 走看看