这个DFS递归函数中的depth + 1和depth++有什么区别?
What's the difference between depth + 1 and depth++ in this DFS recursion function?
我在做leetcode,因为depth++和depth+1的结果完全不一样,搞得一头雾水!我以前以为他们是一样的。谁能解释一下它们的区别?
private void dfs(TreeNode root, List<Integer> res, int depth) {
if (root == null) return;
if (res.size() == depth) {
res.add(root.val);
}
dfs(root.right, res, depth + 1); // depth++ would get different result
dfs(root.left, res, depth + 1);
}
depth++ 与 depth=depth+1
相同。增量运算符将修改 returns 旧 depth
.
的副本
int x = depth;
depth = depth+1;
return x;
depth+1运算将return表达式的值不作任何修改。
return depth+1;
如果您使用 post 赋值递增
int a=1;
a = a++;
- 你可以这么想(a=a++ => a=a 然后a++)
- 现在当我们在赋值期间和赋值后赋值 [a=a++] a = 1 时 a=2
如果您使用 post 无赋值的增量
int x=1;
x++;
- 现在赋值时 x = 2,赋值后 x=2
post增量运算符varName++
使用current值,then 递增变量,然后 继续执行语句的其余部分。
如果您使用 pre 增量运算符 ++varName
,第一个调用将像 depth + 1
一样工作,但是 会使变量递增,需要 next 使用它来考虑这个因素:
dfs(root.right, res, ++depth); // increment before using value
dfs(root.left, res, depth); // depth already incremented
尽管由于避免了 1 次算术运算,这会执行得更快一些,但代码更难阅读,如果添加更多预计 depth
不会在方法。
有些人认为更改方法参数值的风格很差,尽管这种风格指南并未被普遍接受为最佳实践。
depth + 1
和depth++
的结果一样,只是执行的方式不同。
depth = depth + 1
将计算结果应用于下一个操作。
depth++
先对预加值进行运算,然后加一
我在做leetcode,因为depth++和depth+1的结果完全不一样,搞得一头雾水!我以前以为他们是一样的。谁能解释一下它们的区别?
private void dfs(TreeNode root, List<Integer> res, int depth) {
if (root == null) return;
if (res.size() == depth) {
res.add(root.val);
}
dfs(root.right, res, depth + 1); // depth++ would get different result
dfs(root.left, res, depth + 1);
}
depth++ 与 depth=depth+1
相同。增量运算符将修改 returns 旧 depth
.
int x = depth;
depth = depth+1;
return x;
depth+1运算将return表达式的值不作任何修改。
return depth+1;
如果您使用 post 赋值递增
int a=1;
a = a++;
- 你可以这么想(a=a++ => a=a 然后a++)
- 现在当我们在赋值期间和赋值后赋值 [a=a++] a = 1 时 a=2
如果您使用 post 无赋值的增量
int x=1;
x++;
- 现在赋值时 x = 2,赋值后 x=2
post增量运算符varName++
使用current值,then 递增变量,然后 继续执行语句的其余部分。
如果您使用 pre 增量运算符 ++varName
,第一个调用将像 depth + 1
一样工作,但是 会使变量递增,需要 next 使用它来考虑这个因素:
dfs(root.right, res, ++depth); // increment before using value
dfs(root.left, res, depth); // depth already incremented
尽管由于避免了 1 次算术运算,这会执行得更快一些,但代码更难阅读,如果添加更多预计 depth
不会在方法。
有些人认为更改方法参数值的风格很差,尽管这种风格指南并未被普遍接受为最佳实践。
depth + 1
和depth++
的结果一样,只是执行的方式不同。
depth = depth + 1
将计算结果应用于下一个操作。
depth++
先对预加值进行运算,然后加一