package com.heu.wsq.leetcode.tree;
import java.util.Deque;
import java.util.LinkedList;
/**
* 230. 二叉搜索树中第K小的元素
* @author wsq
* @date 2021/3/25
* 给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
*
* 示例 1:
* 输入:root = [3,1,4,null,2], k = 1
* 输出:1
*
* 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst
*/
public class KthSmallest {
/**
* 由于二叉搜索树的中序遍历是递增的数组,因此,通过针对二叉搜索树的一次中序遍历就可以找到第k小的值
* @param root
* @param k
* @return
*/
public int kthSmallest(TreeNode root, int k) {
if(root == null){
return -1;
}
// 使用栈来保存递归的信息
Deque<TreeNode> stack = new LinkedList<>();
TreeNode tmpRoot = root;
while(!stack.isEmpty() || tmpRoot != null){
if(tmpRoot != null){
// 使得stack里面保存root和左节点
TreeNode node = tmpRoot;
while(node != null){
stack.push(node);
node = node.left;
}
}
tmpRoot = stack.pop();
k--;
if(k == 0){
break;
}
if(tmpRoot.right != null){
tmpRoot = tmpRoot.right;
}else{
tmpRoot = null;
}
}
return tmpRoot.val;
}
}