首页 > 代码库 > [LeetCode]103 Binary Tree Zigzag Level Order Traversal
[LeetCode]103 Binary Tree Zigzag Level Order Traversal
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。