LeetCode刷题实战107:二叉树的层次遍历 II
共 1962字,需浏览 4分钟
·
2020-11-26 21:57
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 二叉树的层次遍历 II,我们先来看题面:
https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
题意
解题
class Solution {
public List<List> levelOrderBottom(TreeNode root) {
List<List> levelOrder = new LinkedList<List >();
if (root == null) {
return levelOrder;
}
Queuequeue = new LinkedList ();
queue.offer(root);
while (!queue.isEmpty()) {
Listlevel = new ArrayList ();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val);
TreeNode left = node.left, right = node.right;
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}
}
levelOrder.add(0, level);
}
return levelOrder;
}
}
上期推文: