【LeetCode】103# 二叉树的锯齿形层次遍历
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】103# 二叉树的锯齿形层次遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
返回鋸齒形層次遍歷如下:
[[3],[20,9],[15,7] ]解題思路
考慮到題目需要用折線得方式遍歷,就是說在遍歷的過程中需要有反向操作,可以聯想到使用棧來實現。
雙棧法
源代碼
public List<List<Integer>> zigzagLevelOrder (TreeNode root) {List<List<Integer>> ans = new ArrayList<List<Integer>>();if (root== null) return ans;Stack<TreeNode> stack1 = new Stack<>();Stack<TreeNode> stack2 = new Stack<>();TreeNode cur = root;stack1.push(cur);while (!stack1.isEmpty() || !stack2.isEmpty()) {List<Integer> temp = new ArrayList<>();while (!stack1.isEmpty()) {cur = stack1.pop();temp.add(cur.val);if (cur.left !=null) stack2.push(cur.left);if (cur.right !=null) stack2.push(cur.right);}ans.add(temp);temp = new ArrayList<>();while (!stack2.isEmpty()) {cur = stack2.pop();temp.add(cur.val);if (cur.right !=null) stack1.push(cur.right);if (cur.left !=null) stack1.push(cur.left);}if (!temp.isEmpty()) {ans.add(temp);}}return ans; }心得體會
一開始只用了一個棧和一個列表來實現,怎么也調不通,后來參考了討論區的解答,使用雙棧,豁然開朗。
轉載于:https://www.cnblogs.com/yuzhenzero/p/10254629.html
總結
以上是生活随笔為你收集整理的【LeetCode】103# 二叉树的锯齿形层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LUOGU P4587 [FJOI201
- 下一篇: Jmeter测试Mysql数据库-入门篇