# Binary Tree Zigzag Level Order Traversal

56人阅读 评论(0)

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]
]

public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
int cnt = 0;
int f = 0;
int t = 1;
int index;
List<List<Integer>> lsts = new ArrayList<List<Integer>>();
List<Integer> lst = new ArrayList<Integer>();
List<TreeNode> nodeList = new ArrayList<TreeNode>();
if(root == null){
return 	lsts;
}
index = 0;
while(t != 0){
if(f == t){
t = cnt;
f = 0;
cnt = 0;
lst = new ArrayList<Integer>();
}
else{
TreeNode node = nodeList.get(index ++);
if(node != null){
f ++;
}
if(node.left != null){
cnt ++;
}
if(node.right != null){
cnt ++;
}
}
}
for(int i = 0;i < lsts.size();i++){
if(i%2 == 1){
List<Integer> ls = lsts.get(i);
int from = 0;
int to = ls.size()-1;
while(from < to){
Integer temp = ls.get(from);
ls.set(from,ls.get(to));
ls.set(to,temp);
from ++;
to --;
}
}
}
return 	lsts;
}
}

public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
int cnt = 0;
int f = 0;
int t = 1;
int index;
int flag = 1;
int top = 0;
List<List<Integer>> lsts = new ArrayList<List<Integer>>();
List<Integer> lst = new ArrayList<Integer>();
List<TreeNode> nodeList = new ArrayList<TreeNode>();
if(root == null){
return 	lsts;
}
index = 0;
while(t != 0){
if(f == t){
t = cnt;
f = 0;
cnt = 0;
index =top + t;
top = index;
lst = new ArrayList<Integer>();
if(flag == 1){
flag = 2;
}else{
flag = 1;
}
}
else{
TreeNode node = nodeList.get(index--);
if(node != null){
f ++;
}
if(flag == 1){
if(node.left != null){
cnt ++;
}
if(node.right != null){
cnt ++;
}
}else{
if(node.right != null){
cnt ++;
}
if(node.left != null){
cnt ++;
}
}
}
}

return 	lsts;
}
}

public List<List<Integer>> zigzagLevelOrder(TreeNode root)
{
List<List<Integer>> sol = new ArrayList<>();
travel(root, sol, 0);
return sol;
}

private void travel(TreeNode curr, List<List<Integer>> sol, int level)
{
if(curr == null) return;

if(sol.size() <= level)
{
}

List<Integer> collection  = sol.get(level);
if(level % 2 == 0) collection.add(curr.val);

travel(curr.left, sol, level + 1);
travel(curr.right, sol, level + 1);
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：42140次
• 积分：1041
• 等级：
• 排名：千里之外
• 原创：57篇
• 转载：44篇
• 译文：0篇
• 评论：3条
评论排行