一开始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;
}
};