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

501.Find Mode in Binary Search Tree(Tree-Easy)

作者头像
Jack_Cui
发布2018-01-08 16:10:19
8700
发布2018-01-08 16:10:19
举报
文章被收录于专栏:Jack-CuiJack-Cui

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

题目:找到二叉搜索树中的所有mode(出现最频繁的元素)。

思路:这里定义的二叉搜索树的一个结点的左子树中所有结点的值都小于或等于该结点的值,右子树则相反,大于或等于。于此同时,follow up说让我们不用除了递归中的隐含栈之外的额外空间,因此不能使用哈希表。由于是二叉搜索树,那么我们中序遍历出来的结果就是有序的,我们只需要比较前后两个元素是否相等,就能统计某个元素出现的次数,因为相同的元素可定是都在一起的。我们需要一个结点变量pre来记录上一个遍历到的结点,然后mx记录最大的次数,cnt计数当前元素出现的次数。中序遍历的时候,如果pre不为空,说明当前不是第一个结点,我们和之前一个结点比较,如果相等,则cnt自增1,如果不等,cnt重置1。如果此时cnt大于mx,那么我们清空结果res,并把当前结点值放入结果res,如果cnt等于mx,那么我们直接将当前结点值加入结果res,然后mx赋值为cnt。最后我们把pre更新为当前结点。如果pre为空,说明当前结点是根结点。那么我们新建一个结点并赋上当前结点值。

Language : cpp

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        if (!root) return {};
        vector<int> res;
        TreeNode *now = root, *pre = NULL;
        stack<TreeNode*> s;
        int mx = 0, cnt = 1;
        while (!s.empty() || now) {
            while (now) {             //中序遍历,左中右。将每个结点的左子树入栈
                s.push(now);
                now = now->left;
            }
            now = s.top(); s.pop(); //取栈顶元素
            if (pre) {              //判断当前元素和上一个元素值是否一样,一样cnt计数加一
                cnt = (now->val == pre->val) ? cnt + 1 : 1;
            }                       //如果cnt大于等于mx,说明当前元素重复次数大于之前最大的重复元素的次数,需要将新结果入结果栈。
            if (cnt >= mx) {
                if (cnt > mx) res.clear();
                res.push_back(now->val);
                mx = cnt;
            }
            if (!pre) pre = new TreeNode(now->val);
            pre->val = now->val;
            now = now->right;
        }
        return res;
    }
};

Language : python

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        s = []
        now = root
        pre = None
        mx, cnt = 0, 1
        while s or now:
            while now:
                s.append(now)
                now = now.left
            now = s.pop(len(s) - 1)
            if pre:
                if now.val == pre.val:
                    cnt = cnt + 1
                else:
                    cnt = 1
            if cnt >= mx:
                if cnt > mx:
                    del res[:]
                res.append(now.val)
                mx = cnt
            if not pre:
                pre = TreeNode(now.val)
            pre.val = now.val
            now = now.right
        return res

代码获取: https://github.com/Jack-Cherish/LeetCode

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-07-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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