LeetCode题解-230-Kth Smallest Element in a BST

原题



概览

BST是二叉查找树,它具有如下的性质:左子树中所有节点的值均小于根节点的值,右子树中所有节点的值均大于根节点的值。

解法1使用了迭代法;

解法2使用了递归法。


解法1

解题思路

使用迭代法。由于BST的性质,使用二叉树的中序遍历。中序遍历先访问到的节点的值较小,每访问一个节点计数值+1,当计数值到达K的时候该节点就是要访问的节点。
中序遍历的思路请见: LeetCode题解-94-Binary Tree Inorder Traversal

代码

public class Solution230_iterator {
    public int kthSmallest(TreeNode root, int k) {
        int count = 1;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);

        while (!stack.empty()){
            while (stack.peek() != null){
                TreeNode currentNode = stack.peek();
                stack.push(currentNode.left);
            }
            stack.pop();

            if (!stack.isEmpty()){
                TreeNode currentNode = stack.pop();
                if (k == count++)
                    return currentNode.val;

                stack.push(currentNode.right);
            }
        }
        return -1;
    }
}


解法2

解题思路

自己没有想出来递归方法,因为觉得 public int kthSmallest(TreeNode root, int k) 这样的函数不好构造递归。但是没有想到可以在构造一个新的函数,在 public int kthSmallest(TreeNode root, int k) 中调用该函数。

代码

public class Solution230_recursive {
    private static int count = 0;
    private static int number = 0;

    public int kthSmallest(TreeNode root, int k) {
        count = k;
        helper(root);
        return number;
    }

    private void helper(TreeNode root) {
        if (root.left != null)
            helper(root.left);

        count--;
        if (count == 0) {
            number =  root.val;
            return;
        }
        if (root.right != null)
            helper(root.right);
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值