LeetCode 501 Binary Search Tree HERODING's LeetCode Road

Given a binary search tree (BST) with the same value, find all modes (the most frequent element) in the BST.

Assume that BST has the following definition:

结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树

For example:
given BST [1,null,2,2],

1
\
2
/
2

Return to [2].

Tip: If the mode exceeds 1, no need to consider the output order

Advanced: Can you not use extra space? (Assuming that the overhead of the implicit call stack generated by recursion is not counted)

Problem-solving idea: the problem of
binary search tree, then if the in-order traversal is ascending order, the problem will be solved easily. During the in-order traversal, the number of the same number as the current number and the maximum value of the same number have been saved continuously. If the current number is equal to the maximum value of the saved number, then save the current number. If it is greater than, then clear the saved data and save the current number and number, the code is as follows:

/**
 * 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:
    void inOrder(TreeNode * root, TreeNode *& pre, int& current, int& max, vector<int>& res){
    
    
        if(!root){
    
    
            return;
        }
        //中序遍历,向左
        inOrder(root->left, pre, current, max, res);
        //如果pre存在
        if(pre){
    
    
            if(pre->val == root->val){
    
    
                current ++;
            }else{
    
    
                current = 1;
            }
        }
        // 如果当前数的数量为max
        if(current == max){
    
    
            res.push_back(root->val);
        }
        // 如果当前数的数量大于max
        else if(current > max){
    
    
            res.clear();
            res.push_back(root->val);
            max = current;
        }
        //pre更新
        pre = root;
        inOrder(root->right, pre, current, max, res);
    }

    vector<int> findMode(TreeNode* root) {
    
    
        vector<int> res;
        if(!root){
    
    
            return res;
        }
        TreeNode * pre = NULL;
        int current = 1;
        int max = 0;
        inOrder(root, pre, current, max, res);
        return res;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108765853