首页 > 代码库 > [LeetCode]102 Binary Tree Level Order Traversal
[LeetCode]102 Binary Tree Level Order Traversal
https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
http://blog.csdn.net/linhuanmars/article/details/23404111
/** * 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>> levelOrder(TreeNode root) { // This is how we use queue to iterate a tree. // To let nodes on the same level be returned in the same list, we can store an extra level for each nodes. List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Queue<NodeWithLevel> queue = new LinkedList<>(); queue.offer(new NodeWithLevel(root, 0)); while (!queue.isEmpty()) { NodeWithLevel nodeWithLevel = queue.poll(); if (nodeWithLevel.level == result.size()) result.add(new ArrayList<Integer>()); result.get(nodeWithLevel.level).add(nodeWithLevel.node.val); if (nodeWithLevel.node.left != null) { queue.offer(new NodeWithLevel(nodeWithLevel.node.left, nodeWithLevel.level + 1)); } if (nodeWithLevel.node.right != null) { queue.offer(new NodeWithLevel(nodeWithLevel.node.right, nodeWithLevel.level + 1)); } } return result; } private static class NodeWithLevel { TreeNode node; int level; NodeWithLevel(TreeNode node, int level) { this.node = node; this.level = level; } } }
[LeetCode]102 Binary Tree Level Order Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。