一、思路
思路:
- 二叉搜索树中序遍历得到有序的动态数组
- 按照 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 {
private List<Integer> nodeList = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
inorder(root);
return nodeList.get(k - 1);
}
public void inorder(TreeNode root){
if(root == null){
return ;
}
inorder(root.left);
nodeList.add(root.val);
inorder(root.right);
}
}