Kth Smallest Element in a BST

本文介绍了解决LeetCode上关于二叉搜索树(BST)中寻找第K小元素的问题。提供了两种方法:一种是Morris遍历进行中序遍历,另一种是通过递归计算左子树节点数来进行二分查找。最后讨论了通过修改节点存储左子树节点数以提高查找效率的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Kth Smallest Element in a BST

题目链接:https://leetcode.com/problems...

inorder traverse:

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        // morris: inorder traverse
        TreeNode cur = root, prev = null;
        int count = 0;
        while(cur != null) {
            // reach the end of left part
            if(cur.left == null) {
                if(++count == k) return cur.val;
                cur = cur.right;
            }
            else {
                prev = cur.left;
                // find the right most part
                while(prev.right != null && prev.right != cur) prev = prev.right;
                // reach the end of current right part
                if(prev.right == null) {
                    prev.right = cur;
                    cur = cur.left;
                }
                // recover the tree
                else {
                    prev.right = null;
                    if(++count == k) return cur.val;
                    cur = cur.right;
                }
            }
        }
        
        return -1;
    }
}

二分找结果,按左边nodes数来分:

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int left = getNum(root.left);
        if(left == k - 1) return root.val;
        else if(left < k - 1) return kthSmallest(root.right, k - left - 1);
        else return kthSmallest(root.left, k);
    }
    
    private int getNum(TreeNode node) {
        if(node == null)  return 0;
        // divide and conquer
        return 1 + getNum(node.left) + getNum(node.right);
    }
}

如果改下node,加入number of left的field,那就可以在O(h)时间内找到结果了:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     int leftNum;
 *     TreeNode(int x, int num) { val = x; leftNum = num; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int left = root.leftNum;
        if(left == k - 1) return root.val;
        else if(left < k - 1) return kthSmallest(root.right, k - left - 1);
        else return kthSmallest(root.left, k);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值