前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode501. Find Mode in Binary Search Tree

leetcode501. Find Mode in Binary Search Tree

作者头像
眯眯眼的猫头鹰
发布2019-11-03 12:33:00
3890
发布2019-11-03 12:33:00
举报

题目要求

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],

代码语言:javascript
复制
   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).

现有一个可以包含重复元素的二叉查找树,该二叉查找树满足所有左节点的值均小于等于父节点,所有右节点均大于等于父节点。现要求找出所有出现次数最多的值。

思路和代码

题目中有一个额外的要求,就是只用O(1)的空间复杂度来完成这次计算。这里就复述一下在回答里面一个非常非常棒的解答。即通过两次中序遍历来完成。第一次中序遍历将计算出出现最多的次数。第二次中序遍历则将统计的次数等于第一次计算出的最多次数的结果相等的值加入结果集中。

代码语言:javascript
复制
    int maxCount;
    int curCount;
    int curValue;
    int[] result;
    int modeCount;

    public int[] findMode(TreeNode root) {
        inorder(root);
        result = new int[modeCount];
        curCount = 0;
        modeCount = 0;
        inorder(root);
        return result;
    }

    private void inorder(TreeNode node) {
        if (node == null) {
            return;
        }
        inorder(node.left);
        handle(node.val);
        inorder(node.right);
    }

    private void handle(int val) {
        if (val != curValue) {
            curCount = 0;
            curValue = val;
        }
        curCount++;
        if (curCount > maxCount) {
            modeCount = 1;
            maxCount = curCount;
        }else if (curCount == maxCount) {
            if (result != null) {
                result[modeCount] = curValue;
            }
            modeCount++;
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档