标签:leetcode
https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
http://blog.csdn.net/linhuanmars/article/details/24509105
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { if (root == null) return Collections. emptyList(); List<List<Integer>> lists = new ArrayList<>(); Queue<NodeWithLevel> queue = new LinkedList<>(); queue.offer(new NodeWithLevel(root, 0)); while (!queue.isEmpty()) { NodeWithLevel levelnode = queue.poll(); if (lists.size() == levelnode.level) { lists.add(new ArrayList<Integer>()); } List<Integer> list = lists.get(levelnode.level); if (levelnode.level % 2 == 0) list.add(levelnode.node.val); else list.add(0, levelnode.node.val); if (levelnode.node.left != null) queue.offer(new NodeWithLevel(levelnode.node.left, levelnode.level + 1)); if (levelnode.node.right != null) queue.offer(new NodeWithLevel(levelnode.node.right, levelnode.level + 1)); } return lists; } private static class NodeWithLevel { private TreeNode node; private int level; NodeWithLevel(TreeNode node, int level) { this.node = node; this.level = level; } } }
[LeetCode]103 Binary Tree Zigzag Level Order Traversal
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1599594