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

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条回答 默认 最新

  • threenewbee 2018-11-26 09:40
    关注

    谁说没有修改
    mx = cnt;
    这里不是修改么

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测