LeetcodeBinary Tree Zigzag Level Order Traversal
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeBinary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
题目:
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,#,#,15,7}
,
3 / \\ 9 20 / \\ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
思路:
层序遍历,再将遍历结果改为需要的顺序。。
算法:
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
if (root == null)
return lists;
q.offer(root);
while (!q.isEmpty()) {
List<Integer> list = new ArrayList<Integer>();
int size = q.size();
for (int i = 0; i < size; i++) { // 该层结点数
TreeNode t = q.poll();
list.add(t.val);
if (t.left != null) {
q.offer(t.left);
}
if (t.right != null) {
q.offer(t.right);
}
}
lists.add(list);
}
// 将层序结果改为zagzag顺序
boolean flag = true;
List<List<Integer>> res = new ArrayList<List<Integer>>();
for (List<Integer> ll : lists) {
if (flag) {
res.add(ll);
} else {
List<Integer> tmp = new ArrayList<Integer>();
for (int i = ll.size() - 1; i >= 0; i--) {
tmp.add(ll.get(i));
}
res.add(tmp);
}
flag = !flag;
}
return res;
}
以上是关于LeetcodeBinary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
LeetCodeBinary Tree Level Order Traversal BFS
leetcodeBinary Tree Level Order Traversal