LeetCode.230 Kth Smallest Element in a BST

本文介绍了一种寻找二叉搜索树中第K小元素的方法,通过中序遍历实现了简单有效的查找过程,并讨论了当二叉树频繁变动时如何优化查找效率。

题目:

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?

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

example:

            4

         /     \

     2            6

/      \         /     \

1       3     5      7

分析:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        //给定一颗从左到右的按顺序的二叉树,找出其中第k小的数
        //思路:因为从左到右依次增大的树,那么中序遍历即可满足条件
        List<Integer> list=new ArrayList<>();
        backtrace(root,list,k);
        return list.get(k-1);
    }
    //中序递归
    public void backtrace(TreeNode root,List<Integer> list,int k){
        //出口
        if(list.size()>=k){
            return ;
        }
        if(root.left!=null){
            backtrace(root.left,list,k);
        }
        list.add(root.val);
        if(root.right!=null){
            backtrace(root.right,list,k);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值