230. 二叉搜索树中第K小的元素

小豆丁 1年前 ⋅ 921 阅读
230. 二叉搜索树中第K小的元素
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

 

解析

直接中序遍历搞

class Solution {    
    public int kthSmallest(TreeNode root, int k) {
        //直接中序遍历
        int count = 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode head = root;
        while(!stack.isEmpty()||head!=null){
            while(head!=null){
                stack.push(head);
                head = head.left;
            }
            head = stack.pop();
            count++;
            if(count==k){
                return head.val;
            }
            if(head.right!=null){
                head = head.right;
            }else{
                head = null;
            }
        }
        return -1;
    }
}