1. 程式人生 > >LeetCode230. 二叉搜尋樹中第K小的元素

LeetCode230. 二叉搜尋樹中第K小的元素

給定一個二叉搜尋樹,編寫一個函式 kthSmallest 來查詢其中第 個最小的元素。

說明:
你可以假設 k 總是有效的,1 ≤ k ≤ 二叉搜尋樹元素個數。

示例 1:

輸入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
輸出: 1

示例 2:

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

進階:
如果二叉搜尋樹經常被修改(插入/刪除操作)並且你需要頻繁地查詢第 k 小的值,你將如何優化 kthSmallest

 函式?

思路:將BST的深度優先結果儲存在List中,因為BST的深度優先遍歷結果是按升序排序的,因此只需返回List中第k-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) {
         List<Integer> res=new LinkedList<Integer>();
        dfs(root,res);

        return res.get(k-1);
    }
     public  void dfs(TreeNode root, List<Integer> res){

        if(null==root){
            return ;
        }
        dfs(root.left,res);
        res.add(root.val);
        dfs(root.right,res);
    }

}

解法二:參考LeetCode給的題解,首先遍歷到根結點的最左結點,也就是BST中結點值最小的結點,在以後結束n次遞迴也就是遍歷到第n小的結點。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private static int cnt;
    private static int num;
    public int kthSmallest(TreeNode root, int k) {
        cnt = k;
        helper(root);
        return num;
    }
      private static void helper(TreeNode root){
        if(root.left != null)
            helper(root.left);
        cnt--;
        if(cnt == 0){
            num = root.val;
            return;
        }
        if(root.right != null)
            helper(root.right);
    }

}