How does this recursion work?

前端 未结 11 587
轮回少年
轮回少年 2020-11-30 11:03

This is an example from Eloquent Javascript:

By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of

11条回答
  •  难免孤独
    2020-11-30 11:08

    Think of the infinite combinations of adding 5 and multiplying by 3 like a binary tree. At the top is the easiest number to calculate, 1 (in effect a "no steps necessary" answer). Down one level and to the left is 1+5, and to the right is 1*3. At each level the equation resolves to a new value (with a more complex history). This equation is navigating through that tree until it finds a node that equates to the goal. If a node on a branch of the tree produces a value greater than your goal, then it returns null (thus halting the further recusing down that branch, this is because both operations only increase the value so once you end up greater than there is no point to keep looking), if the value of a node equates to the goal then it is returned as the answer (along with the path it used to get there). When the value is less than then both paths could potentially hold the answer so it calls find on each. Here is where JavaScript's "truthy" Boolean logic comes in. By using the || (OR) operator JavaScript will first look down the +5 side of the tree. if 0 or null are returned then the other call (to look down the *3) will execute. If any return evaluates to a non false value then it will get returned up the stack and the search will end.

提交回复
热议问题