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.
method 1
树的问题一般即树的遍历问题,考虑前序、中序、后序和层序
根据题目意思,可以从小到大遍历二叉树,那么得到便是一串从小到大的序列,第k个即为所求,所以使用中序,并使用一个数组存储
void inOrder(TreeNode* root, int k, vector<int> vals){
if (!root) return;
inOrder(root->left, k, vals);
vals.push_back(root->val);
inOrder(root->right, k, vals);
}
int kthSmallest(TreeNode* root, int k) {
vector<int> vals;
inOrder(root, k, vals);
return vals[k-1];
}
method 2
同样的思想,不过借助一个stack实现迭代(非递归)的方法
class Solution {
public int kthSmallest(TreeNode root, int k) {
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
while (true) {
while (root != null) {
stack.add(root);
root = root.left;
}
root = stack.removeLast();
if (--k == 0) return root.val;
root = root.right;
}
}
}
summary
- 树的问题一般可以归纳为树的遍历顺序问题!