简体   繁体   中英

How to find the kth leaf in an avl tree

i want to solve this by adding a leaf field to my avl tree node to represent leafs below node the leaf field would tell how many leaves are below each node (n->leaves =n->left->leaves + n->right->leaves ) and modify during inserting and deletion. With this, I can move through faster ex if I am looking for 100th leaf and the left subtree has 90 leaves I can directly move to right subtree changing time complexity to O(logn) rather than O(n)

typedef struct tr_n_t { 
//int leaf
    key_t key;
    struct tr_n_t *left;
    struct tr_n_t *right;
    int height; 
} tree_node_t;  

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 k th 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM