• 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树种出现次数最多的数。
    思路:中序遍历,记录先前结点的值和当前结点的值比较,并记录出现的次数。具体实现看代码。

    /**
     * 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> ans;
        int Max = 0;
        void dfs(TreeNode* root, int& pre, int& cn) {
            if (root == nullptr) return ;
            dfs(root->left, pre, cn);
            if (root->val == pre) {
                cn++;
            } else if (pre != -1){
                if (cn > Max) {
                    Max = cn;
                    ans.clear();
                    ans.emplace_back(pre);
                    //cout << root->val << endl;
                } else if (cn == Max) {
                    ans.emplace_back(pre);
                }
                cn = 1;
            }
            //cout << root->val << endl;
            pre = root->val;
            dfs(root->right, pre, cn);
        }
        vector<int> findMode(TreeNode* root) {
            int pre = -1;
            int cn = 1;
            if (root == nullptr) return ans;
            dfs(root, pre, cn);
            if (cn > Max) {
                ans.clear();
                ans.emplace_back(pre);
            } else if (cn == Max) {
                ans.emplace_back(pre);
            }
            return ans;
        }
    };
    
  • 相关阅读:
    python处理url中的中文编码,以及其他编码问题
    深度学习与神经网络
    Windows下为64位的python3.4.3安装numpy
    TOP 10开源的推荐系统简介
    遗传算法
    java调用c++生成的动态和静态库时遇到的问题
    java程序(一)----HashMap同时获取键值
    Deep Learning In NLP 神经网络与词向量
    word2vec使用说明
    Spring入门_02_属性注入
  • 原文地址:https://www.cnblogs.com/pk28/p/8486899.html
Copyright © 2020-2023  润新知