【LeetCode】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.

算法思想

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

阅读更多
版权声明:本文为博主原创文章,欢迎转载并接受错误指正。 https://blog.csdn.net/baidu_22502417/article/details/46776807
上一篇【LeetCode】Power of Two
下一篇【LeetCode】Basic Calculator II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭