/**
* 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 ans, k;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
dfs(root);
return ans;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
k--;
if(k == 0){
ans = root.val;
return;
}
dfs(root.right);
}
}
二叉搜索树中第K小的元素
最新推荐文章于 2024-07-09 13:30:51 发布