首页 > 其他 > 详细

LeetCode 230: Kth Smallest Element in a BST

时间:2015-07-02 15:49:52      阅读:386      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!