美文网首页
230. Kth Smallest Element in a B

230. Kth Smallest Element in a B

作者: xingzai | 来源:发表于2019-05-11 22:16 被阅读0次

题目链接
tag:

  • Medium;
  • Stack;

question:
  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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3

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?

思路:
  这道题给的提示是让我们用BST的性质来解题,最重要的性质是就是左<根<右,那么如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。关于二叉树的中序遍历可以参见我之前的博客Binary Tree Inorder Traversal 二叉树中序遍历,我们来看一种非递归的方法,中序遍历最先遍历到的是最小的结点,那么我们只要用一个计数器,每遍历一个结点,计数器自增1,当计数器到达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 kthSmallest(TreeNode* root, int k) {
        int cnt = 0;
        stack<TreeNode*> sk;
        TreeNode* p = root;
        while (p || !sk.empty()) {
            while (p) {
                sk.push(p);
                p = p->left;
            }
            p = sk.top();
            sk.pop();
            ++cnt;
            if (cnt == k)
                return p->val;
            p = p->right;
        }
        return 0;
    }
};

相关文章

网友评论

      本文标题:230. Kth Smallest Element in a B

      本文链接:https://www.haomeiwen.com/subject/shgfaqtx.html