求二叉树最小深度
class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int depth = 0;while (!queue.isEmpty()) {depth++;int levelSize = queue.size();for (int i = 0; i < levelSize; i++) {TreeNode current = queue.poll();// 如果当前节点是叶子节点,直接返回当前深度if (current.left == null && current.right == null) {return depth;}if (current.left != null) {queue.offer(current.left);}if (current.right != null) {queue.offer(current.right);}}}return depth; // 实际上不会执行到这里,因为BFS会在找到叶子节点时提前返回}
}
class Solution {public int minDepth(TreeNode root) {if (root == null) {return 0;}if(root.left == null && root.right == null){return 1;}int ans = Integer.MAX_VALUE;if(root.left != null){ans = Math.min(minDepth(root.left),ans);}if(root.right != null) ans = Math.min(minDepth(root.right),ans);return ans +1;}
}
单调栈(每日温度)
class Solution {public int[] dailyTemperatures(int[] temperatures) {int lens = temperatures.length;int []res = new int[lens];Deque<Integer> stack = new LinkedList<>();stack.push(0);for(int i = 1;i<lens;i++){if(temperatures[i]<=temperatures[stack.peek()]){stack.push(i);}else{while(!stack.isEmpty() && temperatures[i]> temperatures[stack.peek()]){res[stack.peek()] = i - stack.peek();stack.pop();}stack.push(i);}}return res;}
}
1.为什么要用栈 (有可能有多个数字 但是不符合条件)
由于栈先进后出的性质
遍历温度数组: 如果栈为空:
直接压入当前下标
否则: 如果当前温度 ≤ 栈顶温度: 压入当前下标(维护递减栈)
否则: 循环弹出栈顶元素,直到当前温度 ≤ 栈顶温度或栈为空 每次弹出时记录结果(当前下标 - 栈顶下标) 压入当前下标