• 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;
        }
    };
    
  • 相关阅读:
    Java8实战之Stream流式操作
    类、对象、引用
    java对象的四种引用:强引用、软引用、弱引用和虚引用
    《将博客搬至CSDN》
    **JAVA参数传递方式 (按值传递与引用传递区别)
    JavaWeb--ServletContext
    HttpSessionListener的用法
    SpringMVC优雅的获取HttpSevletRequest及HttpServletResponse简录
    setnx
    JVM命令工具开发
  • 原文地址:https://www.cnblogs.com/pk28/p/8486899.html
Copyright © 2020-2023  润新知