二叉查找树的第 K 个结点

二叉查找树的第 K 个结点

NowCoder

解题思路

利用二叉查找树中序遍历有序的特点。

private TreeNode ret;
private int cnt = 0;

public TreeNode KthNode(TreeNode pRoot, int k) {
    inOrder(pRoot, k);
    return ret;
}

private void inOrder(TreeNode root, int k) {
    if (root == null || cnt >= k)
        return;
    inOrder(root.left, k);
    cnt++;
    if (cnt == k)
        ret = root;
    inOrder(root.right, k);
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要计算二叉查找树的平均查找长度,需要知道树的结构和节点的分布情况。下面是一个使用C++实现的计算平均查找长度的示例代码: ```cpp #include <iostream> // 二叉查找树节点定义 struct Node { int key; Node* left; Node* right; Node(int k) : key(k), left(nullptr), right(nullptr) {} }; // 向二叉查找树中插入节点 Node* insert(Node* root, int key) { if (root == nullptr) { return new Node(key); } if (key < root->key) { root->left = insert(root->left, key); } else if (key > root->key) { root->right = insert(root->right, key); } return root; } // 计算二叉查找树的节点个数 int countNodes(Node* root) { if (root == nullptr) { return 0; } return 1 + countNodes(root->left) + countNodes(root->right); } // 计算二叉查找树的深度 int depth(Node* root) { if (root == nullptr) { return 0; } int leftDepth = depth(root->left); int rightDepth = depth(root->right); return 1 + std::max(leftDepth, rightDepth); } // 计算二叉查找树的平均查找长度 float averageSearchLength(Node* root) { int nodeCount = countNodes(root); int treeDepth = depth(root); return static_cast<float>(treeDepth + 1) / nodeCount; } int main() { Node* root = nullptr; // 向二叉查找树中插入节点 root = insert(root, 10); root = insert(root, 5); root = insert(root, 15); root = insert(root, 3); root = insert(root, 7); // 计算平均查找长度 float avgSearchLength = averageSearchLength(root); // 输出结果 std::cout << "平均查找长度: " << avgSearchLength << std::endl; return 0; } ``` 在上面的代码中,我们首先定义了一个二叉查找树的节点结构。然后使用`insert`函数向树中插入节点。接着,我们实现了`countNodes`函数来计算节点的个数,`depth`函数来计算树的深度。最后,通过调用`averageSearchLength`函数,我们可以计算出二叉查找树的平均查找长度。在示例代码中,我们插入了一些节点,并输出了计算结果。你可以根据自己的需求修改代码来适应不同的场景。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值