码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 230: Kth Smallest Element in a BST

时间:2015-07-02 15:50:38      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Given a binary search tree, write a function kthSmallest to 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元素。

代码如下:

class Solution {
public:
	int calcTreeSize(TreeNode* root){
		if (root == NULL)
			return 0;
		return 1+calcTreeSize(root->left) + calcTreeSize(root->right);		
	}
	int kthSmallest(TreeNode* root, int k) {
		if (root == NULL)
			return 0;
		int leftSize = calcTreeSize(root->left);
		if (k == leftSize+1){
			return root->val;
		}else if (leftSize >= k){
			return kthSmallest(root->left,k);
		}else{
			return kthSmallest(root->right, k-leftSize-1);
		}
	}
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode 230: Kth Smallest Element in a BST

标签:leetcode

原文地址:http://blog.csdn.net/sunao2002002/article/details/46726245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!