力扣热门100题之二叉搜索树中第K小的元素

张开发
2026/4/11 23:31:45 15 分钟阅读

分享文章

力扣热门100题之二叉搜索树中第K小的元素
思路二叉搜索树中序遍历就是升序序列所以这题直接中序遍历到第 k 个就是答案一句话二叉搜索树左 根 右中序遍历 从小到大遍历到第k个节点就是第 k 小元素完整代码实现递归版/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val val; * this.left left; * this.right right; * } * } */ class Solution { int res 0; int count 0; public int kthSmallest(TreeNode root, int k) { inOrder(root, k); return res; } public void inOrder(TreeNode root, int k) { if (root null) return; inOrder(root.left, k); count; if (count k) { res root.val; return; } inOrder(root.right, k); } }

更多文章