[LeetCode]230. Kth Smallest Element in a BST

本文介绍了解决在二叉搜索树(BST)中寻找第K小元素的问题,提供了递归与非递归两种方法实现中序遍历,并讨论了不同情况下的处理策略。

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

找出BST中的第k个节点值


BST的中序遍历就是一个升序数组啊!!!!



数左子树中节点个数num,如果是k - 1个,那么当前root即为所求;如果num大于k,则从左子树中找第k个;否则从右子树中找第k - 1 - num个(即减去左子树中节点个数以及root这一个)

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int num = count(root.left);
        if (num >= k) {
            return kthSmallest(root.left, k);
        } else if (num + 1 < k) {
            // 注意第二个参数
            return kthSmallest(root.right, k - 1 - num);
        }
        return root.val;
    }
    private int count(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + count(root.left) + count(root.right);
    }
}



注意dfs的时候函数调用的时候就要保证root不是null,这样里面就不用判断了

递归二叉树的中序遍历

public class Solution {
    int count = 0;
    int num = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        dfs(root);
        return num;
    }
    private void dfs(TreeNode root) {
        if (root.left != null) {
            dfs(root.left);
        }
        count--;
        if (count == 0) {
            num = root.val;
            return;
        }
        if (root.right != null) {
            dfs(root.right);
        }
    }
}



非递归二叉树的中序遍历

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            if (!stack.isEmpty()) {
                cur = stack.pop();
                k--;
                if (k == 0) {
                    return cur.val;
                }
                cur = cur.right;
            }
        }
        return -1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值