leetcode-230. Kth Smallest Element in a BST

来源:互联网 发布:js获取当前时间加一年 编辑:程序博客网 时间:2024/05/17 03:09

链接:https://leetcode.com/problems/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?
题目的意思:给一个二叉搜索树,然后我们在二叉搜索树当中去查找第k小的树。
直接说思路了:比较简单,中序遍历一次找到第k小的就行了。
AC代码如下

public class Solution {    int n=0;    int k=0;    public int kthSmallest(TreeNode root, int k) {        this.k=k;        return mid(root);    }    public int mid(TreeNode node){        if(node==null){            return Integer.MIN_VALUE;        }        int res=mid(node.left);        if(res!=Integer.MIN_VALUE){            return res;        }        n++;        if(n==k){            return node.val;        }        res=mid(node.right);        if(res!=Integer.MIN_VALUE){            return res;        }        return Integer.MIN_VALUE;    }}
0 0
原创粉丝点击