LC704. 二分查找
//二分查找闭着眼睛都能写出来了
class Solution {
public int search(int[] nums, int target) {
int left = 0,right = nums.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] < target){
left = mid + 1;
}else if(nums[mid] > target){
right = mid - 1;
}else{
return mid;
}
}
return -1;
}
}
LC232. 用栈实现队列
class MyQueue {
private Deque<Integer> instack;
private Deque<Integer> outstack;
/** Initialize your data structure here. */
public MyQueue(){
instack = new LinkedList();
outstack = new LinkedList();
}
/** Push element x to the back of queue. */
public void push(int x) {
instack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(outstack.isEmpty()){
in2out();
}
return outstack.pop();
}
/** Get the front element. */
public int peek() {
if(outstack.isEmpty()){
in2out();
}
return outstack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return instack.isEmpty() && outstack.isEmpty();
}
public void in2out(){
while(!instack.isEmpty()){
outstack.push(instack.pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
LC94. 二叉树的中序遍历
递归以及非递归两种写法
递归闭着眼睛也是可以写出来了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
inorder(root,list);
return list;
}
public void inorder(TreeNode root,List<Integer> list){
if(root == null)
return;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
}
//非递归就是要用栈
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Deque<TreeNode> stack = new LinkedList();
List<Integer> list = new ArrayList();
//第一个条件是进入root节点第二个条件是用与root节点转换回溯的时候判断栈是否为空不退出循环
//继续弹栈
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}