关闭

leetcode 230. Kth Smallest Element in a BST

标签: leetcode
97人阅读 评论(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.

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小的数,直接中序遍历就可以了。迭代比递归快一些。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack =new Stack<TreeNode>();
        int n=0;
        int ans=0;
        while(true){
            while(root!=null){
                stack.push(root);
                root=root.left;
            }
            if(n<k){
                n++;
                TreeNode node=stack.pop();
                root=node.right;
                ans=node.val;
            }
            else{
                return ans;
            }

        }
        //return 0;
    }
}
0
0

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