引用作为形参

 

 

 

一开始count没加引用

/**
 * 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 DFS(TreeNode* root, int value, int count)
    {

        if(root == NULL) return;
        if(root->val != value) count++;
        cout<<count<<endl;
 
        DFS(root->left, value, count);
        DFS(root->right,  value, count);

    }
       
    bool isUnivalTree(TreeNode* root) {

        int value = root->val, count = 0;       
        DFS(root, value, count);
        if(count != 0) return false;
        else return true;
       
    }
};

 

 

 

引用是地址传值,作为引用的形参数值被修改的同时,也修改了对应实参的值。

引用还有另外一个作用,声明这个变量的时候不会浪费额外的内存空间,对引用的形参的操作实际就是对实参的操作。

引用传的是参数而不是参数的拷贝,这样子参数的实际值就可以随之改变了

 

值传递只是值操作,对原来的数据没有影响,操作的对象一般是基本数据类型, 不用引用,实参的值不会随着形参被修改

引用传递则是对原来数据的真实操作,操作对象一般是类,接口,数组这种很常见的包装类型

 

/**
 * 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 DFS(TreeNode* root, int value, int& count)
    {

        if(root == NULL) return;
        if(root->val != value) count++;
        cout<<count<<endl;
 
        DFS(root->left, value, count);
        DFS(root->right,  value, count);

    }
       
    bool isUnivalTree(TreeNode* root) {

        int value = root->val, count = 0;       
        DFS(root, value, count);
        if(count != 0) return false;
        else return true;
       
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值