LeetCode 中级 - Kth Smallest Element in a BST

Kth Smallest Element in a BST

给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第 k 个最小的元素。

说明:

你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

示例 1:

输入: root = [3,1,4,null,2], k = 1
输出: 1

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
输出: 3

分析

由于是二叉搜索树,左子树的所有节点<根节点<右子树的所有节点(没有重复节点),因此我们可以采取中序遍历,先深入到最“左”节点,其必然是最小的元素,之后层层回溯,记录当前节点是倒数第几小的就可以了。

代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private int index,res;

        public int kthSmallest(TreeNode root, int k) {
            if(root.left!=null) kthSmallest(root.left,k);

            if(++index ==k) res = root.val;
            if(root.right!=null) kthSmallest(root.right,k);     
            return res;
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值