求二叉樹最小深度
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.為什么要用棧 (有可能有多個數字 但是不符合條件)
由于棧先進后出的性質?
遍歷溫度數組: 如果棧為空:
直接壓入當前下標
否則: 如果當前溫度 ≤ 棧頂溫度: 壓入當前下標(維護遞減棧)
否則: 循環彈出棧頂元素,直到當前溫度 ≤ 棧頂溫度或棧為空 每次彈出時記錄結果(當前下標 - 棧頂下標) 壓入當前下標