[LeetCode] 230. Kth Smallest Element in a BST

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

题目

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;
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82932432