zhxue_11
2018-11-26 01:55
采纳率: 0%
浏览 504

leetcode 501,为什么要传引用?

 * 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) {
        vector<int> res;
        int mx = 0, cnt = 1;
        TreeNode *pre = NULL;
        helper(root, pre, cnt, mx, res);
        return res;
    }

        //res传引用我能理解,因为要对它做修改。pre, cnt, mx应该只要传值就可以了吧?但是是错的,三个&都不能删,为什么呢?
    void helper(TreeNode *node, TreeNode* &pre, int &cnt, int &mx, vector<int> &res) {
        if (!node) {
            return;
        }
        helper(node->left, pre, cnt, mx, res);
        if (pre) {
            cnt = (pre->val == node->val) ? cnt + 1 : 1;
        }
        if (cnt >= mx) {
            if (cnt > mx) {
                res.clear();
            }
            res.push_back(node->val);
            mx = cnt;
        }
        pre = node;
        helper(node->right, pre, cnt, mx, res);
    }
};

1条回答 默认 最新

相关推荐 更多相似问题