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

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 结构体数组文件读取问题
      • ¥15 写c++代码,第7题说一下使用的计算方法
      • ¥15 postman接口自动化测试报告实践总结
      • ¥15 有关c++的问题,利用相关知识
      • ¥15 求香农编码和解码的matlab代码
      • ¥20 ROS中的TEB局部规划问题
      • ¥20 关于#matlab#的问题:要求测出上面图片中所有同心圆的半径
      • ¥20 epanet软件运行问题
      • ¥15 Python 文件读取
      • ¥60 dpabi进行Alff计算时脑池有干扰信号