lc-230


给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

示例 1:

img

输入:root = [3,1,4,null,2], k = 1
输出:1

示例 2:

img

输入:root = [5,3,6,2,4,null,null,1], k = 3
输出:3

提示:

  • 树中的节点数为 n
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 104

进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * 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) {
        Map<TreeNode, Integer> cntMap = new HashMap<>();
        return findKth(root, cntMap, k);
    }

    private int findKth(TreeNode node, Map<TreeNode, Integer> cntMap, int k) {
        int leftCnt = getNodeCnt(cntMap, node.left);
        int rightCnt = getNodeCnt(cntMap, node.right);
        if (k <= leftCnt) {
            return findKth(node.left, cntMap, k);
        } else if (k == leftCnt + 1) {
            return node.val;
        } else {
            return findKth(node.right, cntMap, k - leftCnt - 1);
        }
    }

    private int getNodeCnt(Map<TreeNode, Integer> cntMap, TreeNode node) {
        if (node == null) {
            return 0;
        }
        if (cntMap.containsKey(node)) {
            return cntMap.get(node);
        }

        int cnt = 1 + getNodeCnt(cntMap, node.left) + getNodeCnt(cntMap, node.right);
        cntMap.put(node, cnt);
        return cnt;
    }

}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !