首页 > 解决方案 > 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).

标签: javarecursion

解决方案


我怀疑你可能会卡在这种语法上,因为它不常被教授,而且我知道我团队中有几个高级 Java 人员,每当他们看到这样的语法时,他们必须停下来并在精神上逐步完成:

int leftCount = node.left == null ? 0 : size(node.left);

这相当于:

int leftCount;
if (node.left == null) { 
  leftCount = 0; 
}
else 
  leftCount = size(node.left)

推荐阅读