Kth Smallest Element in a BST

Given a binary search tree, write a functionkthSmallestto find thekth smallest element in it.

Note:

You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

解题思路:

求BST(二叉排序树)中第k小的数。

方法一:

遍历整棵二叉树,之后进行排序,输出第k个节点的val值即可。代码如下(其中我们采用堆栈,先进后出,从右到左。先序遍历整棵二叉树):

class Solution {public:int kthSmallest(TreeNode* root, int k) {if(root==NULL) return 0;stack<TreeNode*> qu;vector<int> res;qu.push(root);while(!qu.empty()){TreeNode* node=qu.top();qu.pop();res.push_back(node->val);if(node->right!=NULL){qu.push(node->right);}if(node->left!=NULL){qu.push(node->left);}}sort(res.begin(),res.end());return res[k-1];}};方法二:

在二叉搜索树中,找到第K个元素。

算法如下:

1、计算左子树元素个数left。

2、 left+1 = K,则根节点即为第K个元素

left >=k, 则第K个元素在左子树中,

left +1 <k, 则转换为在右子树中,,寻找第K-left-1元素。

代码如下:

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

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

而是自己。在你成功地把自己推销给别人之前,

Kth Smallest Element in a BST

相关文章:

你感兴趣的文章:

标签云: