Is an argument to a function which is a reference to variable treated static
in recursive function? Below is a function for finding kth smallest root in a BST.
int findNode(TreeNode* root, int &k) {
if(root == NULL)
return -1;
// We do an inorder traversal here.
int k1 = findNode(root->left, k);
if(k == 0) return k1; // left subtree has k or more elements.
k--;
if(k == 0) return root->val; // root is the kth element.
return findNode(root->right, k); // answer lies in the right node.
}
int kthsmallest(TreeNode* root, int k) {
return findNode(root, k); // Call another function to pass k by reference.
}
The function kthsmallest
returns the kth smallest node's value.
Node definition:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
}
My question is why is k
passed by reference.
The meaning of k
is relevant to the overall algorithm, not the individual call to findNode
. It is like a countdown timer; the algorithm terminates when k
reaches 0. All the recursive calls contribute to the same countdown.
Passing a reference to a variable in a calling scope solves a similar problem as static
, but it's generally considered a superior technique in software engineering. Globals (e.g. static
) limit a program's scalability.
The moral of the story is not to use names like k
. Call it something like remaining_nodes
.