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

中序遍历

class Solution {
    public int kthSmallest(TreeNode root, int k) {

        ArrayList<Integer> list = new ArrayList<>();
        inorder(root, list);

        return list.get(k - 1);
    }

    /**
     * 中序遍历记录升序的列表,然后返回第k个元素
     */
    public void inorder(TreeNode root, ArrayList<Integer> list){

        if (root == null){
            return;
        }

        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

posted @ 2022-01-05 15:16  振袖秋枫问红叶  阅读(15)  评论(0)    收藏  举报