导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-107.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).

For example:
Given binary tree {3,9,20,#,#,15,7} ,
   3
  / \
 9   20
    / \
   15  7
return its bottom-up level order traversal as:
[
 [15,7],
 [9,20],
 [3]
]

翻译

给出一颗二叉树,返回其自底向上层次遍历的节点值。(例如,从左到右,一层一层的)。
例如,给出一颗二叉树 {3,9,20,#,#,15,7}
   3
  / \
 9   20
    / \
   15  7
返回其自底向上层次遍历如下:
[
 [15,7],
 [9,20],
 [3]
]

将 102. Binary Tree Level Order Traversal 每次add时,改为addFirst:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
int size = queue.size();
while (size-- > 0) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.addFirst(level);
}
return res;
}
}