资讯专栏INFORMATION COLUMN

[Leetcode-Tree] Kth Smallest Element in a BST

Carl / 805人阅读

摘要:解题思路本题需要找的是第小的节点值,而二叉搜索树的中序遍历正好是数值从小到大排序的,那么这题就和中序遍历一个情况。

Kth Smallest Element in a BST
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.

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?

Hint:

Try to utilize the property of a BST.
What if you could modify the BST node"s structure?
The optimal runtime complexity is O(height of BST).

1.解题思路

本题需要找的是第k小的节点值,而二叉搜索树的中序遍历正好是数值从小到大排序的,那么这题就和中序遍历一个情况。

public class Solution {
    Stack s=new Stack();
    public int kthSmallest(TreeNode root, int k) {
        if(root==null) return 0;
        pushLeft(root);
        while(!s.empty()){
            TreeNode node=s.pop();
            if(--k==0) return node.val;
            if(node.right!=null)
                pushLeft(node.right);
        }
        return 0;
    }
    private void pushLeft(TreeNode root){
        TreeNode node=root;
        while(node!=null){
            s.push(node);
            node=node.left;
        }
    }
}

3.Follow up

如果树会经常被更改,为了效率,我们可以对树的构造稍作变更,添加一个属性,来标明该节点拥有的左子树的节点数,而这个Number就是比当前值小的节点个数,这样我们结合二分法,就很容易找到第k个小的节点值。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69784.html

相关文章

  • [Leetcode] Kth Smallest Element in a BST 二叉搜索树第k小节

    摘要:中序遍历复杂度时间空间思路因为左节点小于根节点小于右节点,二叉搜索树的一个特性就是中序遍历的结果就是树内节点从小到大顺序输出的结果。这里采用迭代形式,我们就可以在找到第小节点时马上退出。这样我们就可以用二叉树搜索的方法来解决这个问题了。 Kth Smallest Element in a BST Given a binary search tree, write a function...

    Dean 评论0 收藏0
  • Kth Smallest Element in a BST

    摘要:题目链接二分找结果,按左边数来分如果改下,加入的,那就可以在时间内找到结果了 Kth Smallest Element in a BST 题目链接:https://leetcode.com/problems... inorder traverse: public class Solution { public int kthSmallest(TreeNode root, int...

    Barry_Ng 评论0 收藏0
  • leetcode 315 Count of Smaller Numbers After Self 以

    摘要:题目意思就是要一个个的返回当前的最小值。所以解法自然就是。我们需要找出被打乱的点并返回正确结果。然后将两个不正确的点记录下来,最后回原来正确的值。如果是叶子节点,或者只有一个子树。思想来自于的代码实现。 跳过总结请点这里:https://segmentfault.com/a/11... BST最明显的特点就是root.left.val < root.val < root.right.v...

    inapt 评论0 收藏0
  • [LeetCode] 378. Kth Smallest Element in a Sorted M

    摘要:先放一行,或一列把堆顶的最小元素取出来,取次,如果该有下一行下一列的,放入堆中最小的个元素已经在上面的循环被完了,下一个堆顶元素就是 Problem Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in...

    Shihira 评论0 收藏0
  • 378. Kth Smallest Element in a Sorted Matrix

    Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.Note that it is the kth smallest element in the sorted order, not the...

    makeFoxPlay 评论0 收藏0

发表评论

0条评论

Carl

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<