3
头图

The Kth smallest element in a binary search tree

Title description: Given the root node of a binary search tree root , and an integer k , please design an algorithm to find the smallest element k (counting from 1).

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Inorder traversal of binary tree

The characteristic of binary search tree is that the result of in-order traversal is the order of nodes, so the k-th smallest element is found by in-order traversal. The processing process is as follows:

  • First, judge the special case. If the binary tree is empty, it means that there is no K-th smallest node, and return empty directly;
  • In-order traversal obtains all nodes of the binary search tree, which are arranged in order;
  • It is judged that if k is greater than the number of nodes in the binary tree, it means that there is no node with the smallest K, and returns empty directly;
  • Returns the K-th smallest node.
 import com.kaesar.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class LeetCode_230 {
    public static int kthSmallest(TreeNode root, int k) {
        // 如果二叉树为空,说明没有第K小的节点,直接返回空
        if (root == null) {
            return -1;
        }
        List<Integer> values = new ArrayList<>();

        // 中序遍历得到二叉搜索树的所有节点,是按顺序的
        inOrder(root, values);

        // 如果k大于二叉树的节点数,说明不存在第K小的节点,直接返回空
        if (k > values.size()) {
            return -1;
        }

        // 返回第K小的节点
        return values.get(k - 1);
    }

    /**
     * 二叉树的中序遍历
     *
     * @param root
     * @param values
     */
    private static void inOrder(TreeNode root, List<Integer> values) {
        if (root.left != null) {
            inOrder(root.left, values);
        }
        values.add(root.val);
        if (root.right != null) {
            inOrder(root.right, values);
        }
    }

    public static void main(String[] args) {
        /**
         * 测试用例:
         *     3
         *   1   4
         *    2
         */
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.left.right = new TreeNode(2);

        // 期望输出: 1
        System.out.println(kthSmallest(root, 1));
    }
}
[Daily Message] Our hope is that today is better than yesterday, and tomorrow is too far away for us, it doesn't matter. A person cannot be a firefly in his whole life, he must always be a drilling worker, always on his head, and work hard for the light ahead, not to see what happens behind him. I hope that our past is better because of our past efforts, and today's efforts are for tomorrow's glory.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!