我是递归新手,正在尝试理解这段代码。我正在为一场考试学习,并从斯坦福大学的CIS教育图书馆(Nick Parlante的二叉树)中找到了这个“评论者”。
我理解概念,但当我们在循环内进行递归时,一切都变得混乱了!请帮帮我。谢谢。
countTrees() 的解决方案 (C/C++)
/*
For the key values 1...numKeys, how many structurally unique
binary search trees are possible that store those keys.
Strategy: consider that each value could be the root.
Recursively find the size of the left and right subtrees.
*/
int countTrees(int numKeys) {
if (numKeys <=1) {
return(1);
}
// there will be one value at the root, with whatever remains
// on the left and right each forming their own subtrees.
// Iterate through all the values that could be the root...
int sum = 0;
int left, right, root;
for (root=1; root<=numKeys; root++) {
left = countTrees(root - 1);
right = countTrees(numKeys - root);
// number of possible trees with this root == left*right
sum += left*right;
}
return(sum);
}