@author: sdubrz
@date: 2020.04.20
題號: 103
題目難度: 中等
考察內容: 棧,樹
原題鏈接 https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
題目的著作權歸領釦網絡所有,商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題代碼轉載請聯繫 lwyz521604#163.com
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回鋸齒形層次遍歷如下:
[
[3],
[20,9],
[15,7]
]
通過次數43,767 提交次數80,696
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> list = new LinkedList<>();
if(root==null){
return list;
}
Stack<TreeNode> stack1 = new Stack<>();
stack1.push(root);
boolean postive = true;
while(!stack1.isEmpty()){
Stack<TreeNode> stack2 = new Stack<>();
List<Integer> subList = new LinkedList<>();
while(!stack1.isEmpty()){
TreeNode current = stack1.pop();
subList.add(current.val);
if(postive){
if(current.left!=null){
stack2.push(current.left);
}
if(current.right!=null){
stack2.push(current.right);
}
}else{
if(current.right!=null){
stack2.push(current.right);
}
if(current.left!=null){
stack2.push(current.left);
}
}
}
postive = !postive;
// while(!stack2.isEmpty()){
// stack1.push(stack2.pop());
// }
stack1 = stack2;
list.add(subList);
}
return list;
}
}
在 LeetCode 系統中的提交結果:
執行結果: 通過 顯示詳情
執行用時 : 2 ms, 在所有 Java 提交中擊敗了 26.86% 的用戶
內存消耗 : 39.8 MB, 在所有 Java 提交中擊敗了 7.41% 的用戶