[英]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.我想通过向我的 avl 树节点添加一个叶子字段来表示节点下方的叶子来解决这个问题,叶子字段会告诉每个节点下面有多少叶子(n->leaves =n->left->leaves + n->right ->leaves ) 并在插入和删除过程中修改。 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)
有了这个,如果我正在寻找第 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;
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.在OP的情况下,如果(且仅当)两个
left
和right
节点的成员是NULL
,则该节点是叶节点。
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.由于 OP 的
tree_node_t
类型没有指向父节点的指针,因此可以使用递归函数来执行中序遍历。 The in-order traversal is being used to find the k th leaf node.中序遍历用于查找第k个叶节点。 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.当此计数器达到所需的值
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.