首页 > 代码库 > [LeetCode]107 Binary Tree Level Order Traversal II
[LeetCode]107 Binary Tree Level Order Traversal II
https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
http://blog.csdn.net/linhuanmars/article/details/23414711
/** * 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>> levelOrderBottom(TreeNode root) { // BFS if (root == null) return Collections.<List<Integer>> emptyList(); List<List<Integer>> toReturn = new ArrayList<>(); Queue<TreeNodeWithLevel> queue = new LinkedList<TreeNodeWithLevel>(); queue.offer(new TreeNodeWithLevel(root, 1)); while (!queue.isEmpty()) { TreeNodeWithLevel n = queue.poll(); if (toReturn.size() < n.level) { toReturn.add(0, new ArrayList<Integer>()); } toReturn.get(toReturn.size() - n.level).add(n.node.val); if (n.node.left != null) { queue.offer(new TreeNodeWithLevel(n.node.left, n.level + 1)); } if (n.node.right != null) { queue.offer(new TreeNodeWithLevel(n.node.right, n.level + 1)); } } return toReturn; } private static class TreeNodeWithLevel { int level; TreeNode node; TreeNodeWithLevel(TreeNode node, int level) { this.node = node; this.level = level; } } }
[LeetCode]107 Binary Tree Level Order Traversal II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。