AcWing 70. 二叉搜索树的第k个结点
原题链接
简单
作者:
小轩喵灬
,
2025-01-11 16:30:45
,
所有人可见
,
阅读 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode ret;
private int cnt = 0;
//70. 二叉搜索树的第k个结点
public TreeNode kthNode(TreeNode root, int k) {
inOrder(root, k);
return ret;
}
private void inOrder(TreeNode root, int k) {
if (root == null || cnt >= k) {
return;
}
inOrder(root.left, k);
cnt++;
if (cnt == k) {
ret = root;
}
inOrder(root.right, k);
}
}