LeetCode 230: Kth Smallest Element in a BST
2017-03-18 10:39
417 查看
Given a binary search tree, write a function
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
在二叉搜索树种,找到第K个元素。
算法如下:
1、计算左子树元素个数left。
2、 left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
代码如下:
kthSmallestto find thekth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
在二叉搜索树种,找到第K个元素。
算法如下:
1、计算左子树元素个数left。
2、 left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: // 计算左子树元素个数的函数 int calculateSize(TreeNode* root){ if(root == NULL) return 0; return 1 + calculateSize(root->left) + calculateSize(root->right); } int kthSmallest(TreeNode* root, int k) { if (root == NULL) return 0; int leftSize = calculateSize(root->left); //计算左子树的元素个数 if(k == leftSize+1) // 如果k == 左子树 + 1,那么正好的根节点,因为二叉搜索树的左子树小于根,右子树大于根 return root->val; else if(k <= leftSize) //left >=k, 则第K个元素在左子树中 return kthSmallest(root->left, k); else //eft +1 <k, 则转换为在右子树中,寻找第K-left-1元素。 return kthSmallest(root->right, k-leftSize-1); } };
相关文章推荐
- 【LEETCODE】230-Kth Smallest Element in a BST
- Java for LeetCode 230 Kth Smallest Element in a BST
- [leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值
- LeetCode 230: Kth Smallest Element in a BST
- leetcode230:Kth Smallest Element in a BST(medium)
- [Leetcode 230, Medium] Kth Smallest Element in a BST
- LeetCode - 230 - Kth Smallest Element in a BST
- LeetCode230:Kth Smallest Element in a BST
- LeetCode题解-230-Kth Smallest Element in a BST
- leetcode-230-Kth Smallest Element in a BST
- leetcode——230——Kth Smallest Element in a BST
- leetcode230---Kth Smallest Element in a BST(BST中寻找第K小)
- leetcode 230: Kth Smallest Element in a BST
- [LeetCode-230]Kth Smallest Element in a BST
- LeetCode 230: Kth Smallest Element in a BST
- leetcode 230: Kth Smallest Element in a BST
- leetcode 230: Kth Smallest Element in a BST
- LeetCode 230 Kth Smallest Element in a BST
- leetcode230:Kth Smallest Element in a BST
- Leetcode 230 Kth Smallest Element in a BST