題目
描述
實現(xiàn)一個帶有取最小值min方法的棧嗦锐,min方法將返回當(dāng)前棧中的最小值顶猜。
你實現(xiàn)的棧將支持push
,pop
和 min
操作粤剧,所有操作要求都在O(1)時間內(nèi)完成歇竟。
樣例
如下操作:push(1)
,pop()
抵恋,push(2)
焕议,push(3)
,min()
弧关, push(1)
盅安,min()
返回 1唤锉,2,1
解答
思路
建立兩個棧别瞭,一個保持頂端是最小的數(shù)窿祥,另一個保存剩下的數(shù)據(jù)。
代碼
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param k1 and k2: range k1 to k2.
* @return: Return all keys that k1<=key<=k2 in ascending order.
*/
ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
// write your code here
if(root == null) return result;
if(root.val >= k1 && root.val <= k2){
result.add(root.val);
searchRange(root.left, k1, k2);
searchRange(root.right, k1, k2);
}
else if(root.val < k1){
searchRange(root.right, k1, k2);
}
else if(root.val > k2){
searchRange(root.left, k1, k2);
}
Collections.sort(result);
return result;
}
}