【Leetcode】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.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

這道題其實很好地利用BST的特點就好了,舉個栗子:
     2
   /     \
1         3

我怎麼找到第kth的?如果我能排序的話,是不是特別簡單。所以我一眼就看出來了,這其實不就是中序遍歷放進一個queue就好了麼。。。
當然,這裏要注意,queue和stack在java裏不一樣,stack可以直接new,而queue是一個interface,所以new的時候只能 new LinkedList()或者new ArrayDeque();

然後就是巧用queue做中序遍歷:
package testAndfun;

import java.util.ArrayDeque;
import java.util.Queue;


public class KthSmallestEle {
	Queue<Integer> queue = new ArrayDeque<Integer>();
    
	
    public int kthSmallest(TreeNode root, int k){
        foo(root);
        while(k>1){
            queue.poll();
            k--;
        }
        return queue.poll();
    }
    
    public void foo(TreeNode root) {
    	 if(root.left!=null){
             foo(root.left);
             queue.add(root.val);
             if(root.right!=null){
                 foo(root.right);
             }
         }
         else{
             queue.add(root.val);
             if(root.right!=null){
                 foo(root.right);
             }
         }
    }
    
    class TreeNode{
    	int val;
    	TreeNode left;
    	TreeNode right;
    	TreeNode(int x){
    		val = x;
    	}
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章