1. 程式人生 > >[LeetCode] 230. Kth Smallest Element in a BST

[LeetCode] 230. Kth Smallest Element in a BST

題目

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

思路

題目大意

求搜尋二叉樹 中 第k大的資料。

解題思路

方法一 BST的中序遍歷 為升序

由於 BST的中序遍歷 為陣列的升序排列,對BST 中序遍歷,訪問的第k個數據便是 第k大的資料。

這個用了 非遞迴中序遍歷。

方法二 BST 二分查詢

利用查詢 node的 子結點數量。

對一個 node。若node.left 子結點數量 count為k-1,那麼該node 為第k大的。 若 count 大於 k-1,node = node.left。 若 count 小於 k-1, k -= (count + 1) ,node = node.right;

code

方法一 BST的中序遍歷 為升序

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    Map<TreeNode,Integer> tmap;
    
    public int countSubtree(TreeNode root){
        // if(tmap.containsKey(root))  return tmap.get(root);
if(root == null) return 0; return 1 + countSubtree(root.left) + countSubtree(root.right); } public int kthSmallest(TreeNode root, int k) { // tmap = new HashMap<>(); TreeNode currentNode = root; while(currentNode != null){ int count = countSubtree(currentNode.left); if(count < k-1){ currentNode = currentNode.right; k -= count+1; } else if(count>k-1){ currentNode = currentNode.left; } else return currentNode.val; } return -1; } }

方法二 BST 二分查詢

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode>  stack = new Stack<>();
        TreeNode currentNode = root;
        TreeNode tmp;
        
        while (currentNode != null || !stack.isEmpty()){
            while (currentNode!= null){
                stack.push(currentNode);
                currentNode = currentNode.left;
            }
            if(!stack.isEmpty()){
                tmp = stack.pop();
                if((--k) == 0)  return tmp.val;

                currentNode = tmp.right;
            }
        }
        return -1;
    }
}