給定一個二叉搜索樹,編寫一個函數 kthSmallest 來查找其中第 k 個最小的元素。
說明:
你可以假設 k 總是有效的,1 ≤ k ≤ 二叉搜索樹元素個數。
示例1:
輸入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
輸出: 1
示例2:
輸入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
輸出: 3
【思路】
這是一個二叉搜索樹,所以按照中序遍歷的話,其遍歷的次序就是從小到大,於是就可以按照中序遍歷來實現。
【實現代碼】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int res=0;
private int count=0;
public int kthSmallest(TreeNode root, int k) {
count=k;
dfs(root);
return res;
}
private void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
count--;
if(count==0)
this.res=root.val;
dfs(root.right);
}
}