LeetCode Kth Smallest Element in a BST DFS

本文介绍了在二叉搜索树(BST)中寻找第K小元素的三种方法:递归深度优先搜索(DFS)、迭代中序遍历及通过记录左子树节点数量优化查找过程。其中最优方案的时间复杂度可达O(logN)。

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

思路:

方法一 & 二:
中序遍历BST,第K个遍历到的节点就是第K小的元素。

缺点:每次找都要遍历整个BST,需要O(N)的时间复杂度(其中N为节点个数)和维护一个栈的开销。题目给了hint:可以修改树的节点的结构使得复杂度降低到O(logN)。


java code(iterative):

/**
 * 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) {
        if(root == null) return 0;
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode node = root;
        while(node != null) {
            s.push(node);
            node = node.left;
        }
        int count = 0;
        while(!s.empty() && count < k) {
            node = s.peek();
            s.pop();
            count++;
            TreeNode cur = node.right;
            while(cur != null) {
                s.push(cur);
                cur = cur.left;
            }
        }
        return node.val;
    }
}

java code:(DFS)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int number = 0;
    private int count = 0;
    private void dfs(TreeNode cur) {
        if(cur.left != null) {
            dfs(cur.left);
        }
        count--;
        if(count == 0) {
            number = cur.val;
            return;
        }
        if(cur.right != null) {
            dfs(cur.right);
        }
    }
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        dfs(root);
        return number;
    }
}

方法三:

计算每个节点的左子树的节点个数:

  1. 如果左子树的节点个数 >= k :则从左子树中找;

  2. 如果左子树的节点个数 + 1== k :则当前节点就是要找的节点;

  3. 如果左子树的节点个数 + 1 < k:则从右子树中找第 k - count - 1 的节点就好;

时间复杂度:O(logN)。


java code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int countNodes(TreeNode node) {
        if(node == null) return 0;
        return 1 + countNodes(node.left) + countNodes(node.right);
    }
    public int kthSmallest(TreeNode root, int k) {
        int count = countNodes(root.left);
        if(k <= count) {//in the bst's left side
            return kthSmallest(root.left, k);
        }else if(k == count + 1) {
            return root.val;
        }else {//k > count + 1
            return kthSmallest(root.right, k - count - 1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值