Description
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Examples
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 <= 1 0 4 10^4 104
0 <= Node.val <= 1 0 4 10^4 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?
思路
最开始的时候没有看到 “a binary search tree”,所以用的是广度优先搜索的方式,跑了一下看时间不对呀
后面看到了,直接按照深度优先搜索(左子树 - root - 右子树),找到第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 {
public int kthSmallest(TreeNode root, int k) {
List<TreeNode> nodeList = new ArrayList<>();
nodeList.add(root);
List<Integer> route = new ArrayList<>();
route.add(Integer.MAX_VALUE);
while(nodeList.size() > 0){
if (nodeList.get(0) == null){
nodeList.remove(0);
continue;
}
int curr = nodeList.get(0).val;
int max_len = Math.min(route.size() - 1, k - 1);
while(max_len >= 0 && route.get(max_len) > curr){
max_len--;
}
route.add(max_len + 1, curr);
nodeList.add(nodeList.get(0).left);
nodeList.add(nodeList.get(0).right);
nodeList.remove(0);
}
return route.get(k - 1);
}
}
搜索树
/**
* 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 {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
while (true) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (k == 1) {
return root.val;
}
k--;
root = root.right;
}
}
}