思路分析:

题目中提到二叉搜索树,考察的是二叉搜索树与中序遍历的特性。

二叉搜索树特性如下:

  • 节点的左子树只包含小于当前节点的数;
  • 节点的右子树只包含大于当前节点的数;
  • 所有左子树和右子树自身也都必须是二叉搜索树。

中序遍历的特性为:先访问左节点,再访问中节点,最后再访问右节点,简记为 “左中右”。

所以想要找到二叉搜索树第 k 个小的元素,只需要中序遍历二叉树返回第三个元素即可。

示例代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        // 二叉搜索树,采用 中序遍历 左中右
        List<Integer> nodeList = new ArrayList<>();
        traversal(root, nodeList);
        return nodeList.get(k - 1);
        
    }

    public void traversal(TreeNode curr, List<Integer> nodeList) {
        if (curr == null) {
            return;
        }
        traversal(curr.left, nodeList);
        nodeList.add(curr.val);
        traversal(curr.right, nodeList);
    }
}

利用递归的方法遍历整棵二叉树,并将节点元素存入集合中,最后返回集合第 k 个元素即可。遍历二叉树的时间复杂度为 O(log n),按索引下标查询集合元素时间复杂度为 O(1),总的时间复杂度为 O(log n)。

Categories:

Tags:

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注