剑指offer之21-25题解
劍指offer之21-25題解
目錄
21. 棧的壓入,彈出序列
(一)題目描述
輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
(二) 思路
(三)代碼實現
import java.util.Stack; public class Solution {public boolean IsPopOrder(int[] pushA, int[] popA) {int n = pushA.length;Stack<Integer> stack = new Stack<>();for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) {stack.push(pushA[pushIndex]);while (popIndex < n && !stack.isEmpty() && stack.peek() == popA[popIndex]) {stack.pop();popIndex++;}}return stack.isEmpty();} }22. 從上往下打印二叉樹
(一)題目描述
從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
(二) 思路
(三)代碼實現
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class Solution {public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {Queue<TreeNode> queue = new LinkedList<>();ArrayList<Integer> ret = new ArrayList<>();queue.offer(root);while (!queue.isEmpty()){int cnt = queue.size();while (cnt-->0){TreeNode t = queue.poll();if (t == null)continue;ret.add(t.val);queue.offer(t.left);queue.offer(t.right);}}return ret;} }23. 二叉搜索樹的后序遍歷序列
(一)題目描述
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的后序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
注:二叉搜索樹中序遍歷就是遞增的,如下的中序遍歷為1,2,3.
(二) 思路
(三)代碼實現
public class Solution {public boolean VerifySquenceOfBST(int[] sequence) {if (sequence == null || sequence.length == 0) return false;return verify(sequence, 0, sequence.length - 1);}private boolean verify(int[] sequence, int first, int last) {if (last - first <= 1)return true;int rootVal = sequence[last];int cutIndex = first;while (cutIndex < last && sequence[cutIndex] <= rootVal) cutIndex++;for (int i = cutIndex; i < last; i++) if (sequence[i] < rootVal) return false;return verify(sequence, first, cutIndex - 1) && verify(sequence, cutIndex, last - 1);} }24. 二叉樹中和為某一值的路徑
(一)題目描述
輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)
(二) 思路
(三)代碼實現
public class Solution {private ArrayList<ArrayList<Integer>> ret = new ArrayList<>();public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {backtracking(root, target, new ArrayList<Integer>());return ret;}private void backtracking(TreeNode node, int target, ArrayList<Integer> path) {if (node == null)return;path.add(node.val);target -= node.val;if (target == 0 && node.left == null && node.right == null) {ret.add(new ArrayList<>(path));} else {backtracking(node.left, target, path);backtracking(node.right, target, path);}path.remove(path.size() - 1);} }25. 復雜鏈表的復制
(一)題目描述
輸入一個復雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果為復制后復雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
(二) 思路
(三)代碼實現
總結
以上是生活随笔為你收集整理的剑指offer之21-25题解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer之16-20题解
- 下一篇: 剑指offer之26-30题解