230. Kth Smallest Element in a BST
2017-02-22 23:21
260 查看
题目
Given a binary search tree, write a function kthSmallest to find the kth 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小的节点值代码
/** * 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 getCount(TreeNode* node) { if(node == NULL) { return 0; } return 1 + getCount(node->left) + getCount(node->right); } int kthSmallest(TreeNode* root, int k) { int leftCount = getCount(root->left); //左子树个数比k多 if(leftCount >= k) { return kthSmallest(root->left,k); } else if(leftCount < k-1) { //第k小的在右子数 return kthSmallest(root->right,k-leftCount-1); } //刚好是根节点 return root->val; } };
相关文章推荐
- 230. Kth Smallest Element in a BST
- LeetCode#230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历是有序序列
- LeetCode 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- leecode 解题总结:230. Kth Smallest Element in a BST
- 【leetcode】230. Kth Smallest Element in a BST
- <LeetCode OJ> 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST(unsolved)
- leetcode_230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- [LeetCode] Algorithms-45. 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST | 二叉排序树中查找第K小的数
- 230. Kth Smallest Element in a BST
- LeetCode *** 230. Kth Smallest Element in a BST
- LeetCode 230. Kth Smallest Element in a BST 解题报告