[LeetCode] 103. Binary Tree Zigzag Level Order Traversal
阿新 • • 發佈:2018-12-12
題目
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ]
思路
題目大意
給定一個二叉樹,對樹進行層遍歷,但層遍歷方向會變化,開始從左到右,然後從右到左,不斷變化。
解題思路
方法一 樹的層遍歷 ,層的遍歷結果翻轉
對樹進行層遍歷,將特定層的遍歷結果進行翻轉操作。
方法二 stack 實現上層先遍歷的結點的子結點下層後遍歷
stack 實現上層先遍歷的結點的子結點下層後遍歷,從而 產生 本層從左到右遍歷 下層從右到左遍歷。
code
方法一 樹的層遍歷 ,層的遍歷結果翻轉
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
List<TreeNode> lst = new LinkedList<>();
if(root==null) return res;
int ilayer = 1;
boolean isFromLeft;
lst.add(root);
while (!lst.isEmpty()){
List<Integer> eleres = new ArrayList<>();
int layerlen = lst.size();
for(int i = 0 ;i <layerlen ; i++){
TreeNode tnode = lst.get(0);
lst.remove(0);
eleres.add(tnode.val);
if(tnode.left != null) lst.add(tnode.left);
if(tnode.right !=null) lst.add(tnode.right);
}
if(ilayer%2==1){
isFromLeft = true;
}
else {
isFromLeft = false;
}
if(!isFromLeft){
for(int i = 0 ,j = eleres.size() - 1;i<j;i++,j--){
Integer tmp = eleres.get(i);
eleres.set(i,eleres.get(j));
eleres.set(j,tmp);
}
}
res.add(eleres);
ilayer++;
}
return res;
}
}
方法二 stack 實現上層先遍歷的結點的子結點下層後遍歷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root==null) return res;
int ilayer = 1;
boolean isFromLeft = true;
stack.push(root);
while (!stack.isEmpty()){
List<Integer> eleres = new ArrayList<>();
Stack<TreeNode> tstack = new Stack<>();
while (!stack.isEmpty()){
TreeNode tnode = stack.pop();
eleres.add(tnode.val);
if(ilayer %2 == 1){
if(tnode.left != null) tstack.push(tnode.left);
if(tnode.right != null) tstack.push(tnode.right);
}
else {
if(tnode.right != null) tstack.push(tnode.right);
if(tnode.left != null) tstack.push(tnode.left);
}
}
res.add(eleres);
ilayer ++;
stack = tstack;
}
return res;
}
}