标签:
题目链接: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; }
【Leetcode】Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://blog.csdn.net/yeqiuzs/article/details/51527074