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

找出BST的众数,要求不使用额外空间。自然是利用递归进行遍历,由于是BST,所以在中序遍历序列中,相等元素是在一起的,所以我们可以用三个变量存储上一次遍历的数值、上一次数值的出现次数和当前众数的出现次数,那么根据当前元素和上一次元素的比较,我们更新这三个变量,得到最终的众数。

class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        vector<int> result;
        if(root==NULL) return result;
        int pre=INT_MIN;
        int count=0;
        int max_count=0;
        inorder(root,pre,count,max_count,result);
        return result;
    }
    
    void inorder(TreeNode* root, int& pre, int& count, int& max_count, vector<int>& result)
    {
        if(root==NULL) return;
        inorder(root->left,pre,count,max_count,result);
        if(root->val==pre) count++;
        else
        {
            pre=root->val;
            count=1;
        }
        
        if(count==max_count) result.push_back(root->val);
        else if(count>max_count)
        {
            result.clear();
            result.push_back(root->val);
            max_count=count;
        }
        inorder(root->right,pre,count,max_count,result);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值