A node is a leaf if it has no child nodes. In OP's case, if (and only if) both the left
and right
members of a node are NULL
, then the node is a leaf node.
Since OP's tree_node_t
type has no pointer to the parent node, a recursive function can be used to perform an in-order traversal. The in-order traversal is being used to find the kth leaf node. A counter can be used to keep track of how many leaf nodes have been encountered so far. When this counter reaches the desired value k
, the desired leaf node has been found so the function can return a pointer to the desired node, otherwise it should return 0.
// recursive helper function
static tree_node_t *find_leaf_k_internal(tree_node_t *node, unsigned int *count, unsigned int k)
{
tree_node_t *kth;
if (!node)
return NULL; // not a node
if (!node->left && !node->right) {
// node is a leaf
if (*count == k)
return node; // node is the kth leaf
(*count)++; // increment leaf counter
return NULL; // not the kth leaf
}
// node is not a leaf
// perform in-order traversal down the left sub-tree
kth = find_leaf_k_internal(node->left, count, k);
if (kth)
return kth; // return found kth leaf node
// kth leaf node not found yet
// perform in-order traversal down the right sub-tree
return find_leaf_k_internal(node->right, count, k);
}
// find kth in-order leaf node of tree counting from 0.
// returns pointer to kth leaf node, or NULL if tree contains fewer than k+1 leaf nodes.
tree_node_t *find_leaf_k(tree_node_t *root, unsigned int k)
{
unsigned int count = 0; // in-order running count of leaf nodes
return find_leaf_k_internal(root, &count, k);
}