[Sword Finger Offer-tree] Mode in Binary Search Tree

Title description

Given a binary search tree (BST) with the same value, find all modes (elements with the highest frequency) in BST.
Assume that BST has the following definition:

  • The value of the node contained in the left subtree of the node is less than or equal to the value of the current node
  • The value of the node contained in the right subtree of the node is greater than or equal to the value of the current node
  • Both the left and right subtrees are binary search trees

Examples:

例如:
给定 BST [1,null,2,2],
   1
    \
     2
    /
   2
返回[2].

Title link: https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/

Ideas

The binary search tree has an important property: the middle-order traversal sequence of the binary search tree is an ascending sequence. Therefore, we traverse the ascending sequence of node values ​​in the binary search tree, and then find the mode according to the ascending sequence. The way to find the majority:

  • Put the first element of the sequence into the result, record the maximum number of occurrences of the current element as curMax and initialize to 1, and record the number of occurrences of the current element as 1;
  • Start traversing from the second element, if the current element and the previous element are equal, then cnt ++;
    • If cnt == curMax, the current element is assumed to be in the result;
    • If cnt> curMax, it means that a mode with more occurrences is found, the result is cleared, and the current element is added to the result;
  • If the current element is not equal to the previous element, set cnt to 1.

code show as below:

/**
 * 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==nullptr) return {};

        vector<int> v;
        inOrder(root, v);
        
        int cnt = 1;
        int curMax = 1;
        vector<int> ans;
        ans.push_back(v[0]);
        for(int i=1; i<v.size(); i++){
            if(v[i]==v[i-1]){
                cnt++;
            }else cnt=1;
            if(cnt==curMax){
                ans.push_back(v[i]);
            }else if(cnt>curMax){
                curMax = cnt;
                ans.clear();
                ans.push_back(v[i]);
            }
        }
        return ans;
    }

    void inOrder(TreeNode* root, vector<int>& v){
        if(root==nullptr) return;

        inOrder(root->left, v);
        v.push_back(root->val);
        inOrder(root->right, v);
    }
    
};
  • Time complexity: O (h + n)
    h is the tree depth, and n is the number of nodes.
  • Space complexity: O (n)
    n is the number of nodes.

Guess you like

Origin www.cnblogs.com/flix/p/12694990.html