LeetCode - 230. Kth Smallest Element in a BST

这道题目需要利用BST的性质,就是如果对BST进行中序遍历的话,得到的序列的一定是sorted,所以一开始使用了一个ArrayList存储访问的元素,然后返回第k - 1个。但是这种方法不太好,更好的方法是利用k,在访问的过程中,每访问到一个结点就将k的值-1,当k == 0的时候,直接返回当前结点即可。时间复杂度为O(k),三种方式的代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// Method One: Inorder traverse(recursive)
public class Solution {
    ArrayList<Integer> result = new ArrayList<Integer>();

    public void inOrderBST(TreeNode root){
        if(root == null) return;
        
        inOrderBST(root.left);
        result.add(root.val);
        inOrderBST(root.right);
    }
    
    public int kthSmallest(TreeNode root, int k) {
        if(root == null || k < 1) return 0;
        
        inOrderBST(result);
        return result.get(k - 1);
    }
}


// Method Two: Inorder traverse(keep k--)
public class Solution{
    // better keep these two variables in a wrapper class
    private static int number = 0;
    private static int count = 0;

    public int kthSmallest(TreeNode root, int k) {
        count = k;
        helper(root);
        return number;
    }
    
    public void helper(TreeNode n) {
        if (n.left != null) helper(n.left);
        count--;
        if (count == 0) {
            number = n.val;
            return;
        }
        if (n.right != null) helper(n.right);
    }
}

// Method Three: Inorder traverse(iterative)
public int kthSmallest(TreeNode root, int k){
    Stack<TreeNode> stack = new Stack<>();

    while(root != null){
        stack.push(root);
        root = root.left;
    }

    while(k != 0){
        TreeNode node = stack.pop();
        k--;

        if(k == 0) return node.val;

        TreeNode right = node.right;
        while(right != null){
            stack.push(right);
            right = right.left;
        }
    }

    return -1;
}


知识点:

1. 注意利用BST inorder traversal的性质

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值