【题目描述】
Acwing 70. 二叉搜索树的第k个结点
【思路】
二叉搜索树的中序遍历 对应升序序列
那么第k小就是遍历的第k个数
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode ans;
int k; // k 要设置成全局变量
public void inorder(TreeNode node){
if( node == null ) return;
inorder(node.left);
k --;
if( k == 0){
ans = node;
return;
}
inorder(node.right);
}
public TreeNode kthNode(TreeNode root, int _k) {
k = _k;
inorder(root);
return ans;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int index = 0;
TreeNode [] nums = new TreeNode[10000];
public void midTraverse (TreeNode root) {
if (root == null) return;
// 左根右
midTraverse(root.left);
nums[index ++] = root;
midTraverse(root.right);
}
public TreeNode kthNode(TreeNode root, int k) {
/**
二叉搜索树的中序遍历结果就是升序的序列
**/
midTraverse(root);
return nums[k - 1];
}
}