Given the root
of a binary search tree, and an integer k
, return the kth
(1-indexed) smallest element in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Constraints:
- The number of nodes in the tree is
n
. 1 <= k <= n <= 104
0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
二叉搜索树中第K小的元素。
因为是BST所以大概率会碰到中序遍历inorder traversal,这一题也不例外。思路就是按照中序遍历的方法去遍历BST的节点,用count记录是否到K,输出第K个节点即可。影子题671。
时间O(n)
空间O(n)
Java递归实现
1 class Solution { 2 private static int count; 3 private static int res; 4 5 public int kthSmallest(TreeNode root, int k) { 6 count = k; 7 helper(root); 8 return res; 9 } 10 11 public void helper(TreeNode root) { 12 if (root == null) { 13 return; 14 } 15 helper(root.left); 16 count--; 17 if (count == 0) { 18 res = root.val; 19 } 20 helper(root.right); 21 } 22 }
Java迭代实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int kthSmallest(TreeNode root, int k) { 12 Stack<TreeNode> stack = new Stack<>(); 13 while (root != null || !stack.isEmpty()) { 14 if (root != null) { 15 stack.push(root); 16 root = root.left; 17 } else { 18 root = stack.pop(); 19 k--; 20 if (k == 0) { 21 return root.val; 22 } 23 root = root.right; 24 } 25 } 26 return Integer.MIN_VALUE; 27 } 28 }
JavaScript递归实现
1 /** 2 * @param {TreeNode} root 3 * @param {number} k 4 * @return {number} 5 */ 6 var kthSmallest = function (root, k) { 7 let count = k; 8 let res = 0; 9 10 let helper = function (root) { 11 if (root == null) { 12 return; 13 } 14 helper(root.left); 15 count--; 16 if (count == 0) { 17 res = root.val; 18 } 19 helper(root.right); 20 } 21 helper(root); 22 return res; 23 };
JavaScript迭代实现
1 /** 2 * @param {TreeNode} root 3 * @param {number} k 4 * @return {number} 5 */ 6 var kthSmallest = function (root, k) { 7 let stack = []; 8 while (root != null || stack.length > 0) { 9 if (root != null) { 10 stack.push(root); 11 root = root.left; 12 } else { 13 root = stack.pop(); 14 k--; 15 if (k == 0) { 16 return root.val; 17 } 18 root = root.right; 19 } 20 } 21 return -1; 22 };
相关题目
230. Kth Smallest Element in a BST