关闭

【LeetCode】Kth Smallest Element in a BST

标签: BST二叉树中序遍历第i最小元素leetcode
391人阅读 评论(0) 收藏 举报
分类:

问题描述

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.

算法思想

BST中序遍历为排序序列,直接技术前k个访问的数即可得到第k个最小的元素

算法实现

public class Solution {
    private int num = 0;
    private int c = 0;
    public void helper(TreeNode root, int k) {
        if(root.left != null) {
            helper(root.left, k);
        }

        c++;
        if (k == c){
            num = root.val;
            return;
        }

        if (root.right != null) {
            helper(root.right, k);
        }
    }
    public int kthSmallest(TreeNode root, int k) {
         helper(root,k);
         return num;
    }
}

算法时间

T(n) = O(lgn)

演示结果

这里写图片描述

public static void main(String[] args) {
        TreeNode root = new TreeNode(8);
        TreeNode l1 = new TreeNode(1);
        TreeNode l2 = new TreeNode(3);
        TreeNode l3 = new TreeNode(6);
        TreeNode l4 = new TreeNode(4);
        TreeNode l5 = new TreeNode(7);
        TreeNode l6 = new TreeNode(10);
        TreeNode l7 = new TreeNode(14);
        TreeNode l8 = new TreeNode(13);
        root.left = l2;
        root.right = l6;
        l2.left = l1;
        l2.right = l3;
        l3.left = l4;
        l3.right = l5;
        l6.right = l7;
        l7.left = l8;
        Solution s = new Solution();
        s.kthSmallest(root,3);
        System.out.println(s.num);
    }

4

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20994次
    • 积分:572
    • 等级:
    • 排名:千里之外
    • 原创:34篇
    • 转载:4篇
    • 译文:1篇
    • 评论:2条
    最新评论