繁体   English   中英

如何在avl树中找到第k片叶子

[英]How to find the kth leaf in an avl tree

我想通过向我的 avl 树节点添加一个叶子字段来表示节点下方的叶子来解决这个问题,叶子字段会告诉每个节点下面有多少叶子(n->leaves =n->left->leaves + n->right ->leaves ) 并在插入和删除过程中修改。 有了这个,如果我正在寻找第 100 片叶子并且左子树有 90 片叶子,我可以更快地移动我可以直接移动到右子树将时间复杂度更改为 O(logn) 而不是 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;  

如果一个节点没有子节点,它就是一个叶子节点。 在OP的情况下,如果(且仅当)两个leftright节点的成员是NULL ,则该节点是叶节点。

由于 OP 的tree_node_t类型没有指向父节点的指针,因此可以使用递归函数来执行中序遍历。 中序遍历用于查找第k个叶节点。 计数器可用于跟踪到目前为止遇到了多少叶节点。 当此计数器达到所需的值k ,已找到所需的叶节点,因此该函数可以返回指向所需节点的指针,否则应返回 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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