[英]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的情況下,如果(且僅當)兩個left
和right
節點的成員是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.