java - How this recursive call gets executed?
问题描述
The following is a snippet to find the size of tree.How leftCount and rightCount values gets calculated at each recursive call.I understand recursion basically(which is each call gets into stack and returned when that called function is complete) but i cant visualize in this snippet.Can someone tell me how ?
public static int size(Node node){
int leftCount = node.left == null ? 0 : size(node.left);
int rightCount = node.right == null ? 0 : size(node.right);
return 1+leftCount+rightCount;
}
Edit : I understand recursions say return n * fact(n-1)
.But in the above snippet there are two variables and their return statement makes use of both those variables so its kinda tough for me to understand.If this is too broad to explain can anyone post a simpler example with similar situation (using two variables).
解决方案
我怀疑你可能会卡在这种语法上,因为它不常被教授,而且我知道我团队中有几个高级 Java 人员,每当他们看到这样的语法时,他们必须停下来并在精神上逐步完成:
int leftCount = node.left == null ? 0 : size(node.left);
这相当于:
int leftCount;
if (node.left == null) {
leftCount = 0;
}
else
leftCount = size(node.left)
推荐阅读
- python - Jupyter Python 上的 MiniZinc
- python - 在python中删除文本文件中的空格
- sql - Sql Server 全局阻止列表和项目特定允许列表
- python - 用 3 个向量绘制轮廓
- php - SQLSTATE[HY000] [2002] 连接被拒绝 Laravel 8
- activecollab - 在 Active Collab 上重新打开已完成的项目
- c# - ASP.NET C# 将链接按钮添加到列表
- python - 使用数据帧中的关键字来检测另一个数据帧或字符串中是否存在任何关键字
- ios - SwiftUI 中有没有办法检测用户是否启用了较大的文本大小?
- excel - 为什么我的 redim 保留导致类型不匹配错误?