如何用递归实现三值求和(JavaScript)及二叉树节点总和返回
Hey there! Let's work through these two JavaScript recursion problems together.
1. Recursive Sum of Three Numbers (JavaScript)
To sum three numbers recursively, we can lean into recursion's core idea: breaking the problem into smaller subproblems until we hit a simple base case. Here's how you can do it:
The base case is when we're left with just one number—we just return that number. For the recursive step, we take the first number and add it to the sum of the remaining two numbers (calculated by calling the function again with those two values).
function sumThree(num1, num2, num3) { // Base case: if we've whittled down to a single number, return it if (num2 === undefined && num3 === undefined) { return num1; } // Recursive step: add the current number to the sum of the rest return num1 + sumThree(num2, num3); } // Test example console.log(sumThree(1, 2, 3)); // Output: 6
If you want a more flexible version that works for any number of inputs (including three), you could use rest parameters, but the above is tailored specifically to three values as requested.
2. Sum All Node Values in a Binary Tree (No Extra Parameters)
Your existing code does a great job of traversing the tree and printing values—now we just need to adjust it to return the sum instead of logging. The key here is to use recursion's return values to accumulate the total:
- Base case: If the current
rootisnull, return 0 (since an empty node contributes nothing to the sum). - Recursive step: Return the current node's value plus the sum of all nodes in the left subtree, plus the sum of all nodes in the right subtree.
Here's the modified code:
const nodes = { value: 7, left: { value: 1, left: null, right: null }, right: { value: 4, left: null, right: null } }; sumTheTreeValues = root => { // Base case: empty node adds 0 to the sum if (!root) return 0; // Add current value to the sum of left and right subtrees return root.value + sumTheTreeValues(root.left) + sumTheTreeValues(root.right); }; console.log(sumTheTreeValues(nodes)); // Output: 12
This works because each recursive call returns the sum of its own subtree. When we add those returns together with the current node's value, we build up the total sum of the entire tree—no extra parameters needed to track the running total!
内容的提问来源于stack exchange,提问作者Seinfeld

