友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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 from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

   3
  / \
 9  20
   /  \
  15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

解题分析

分层访问,然后再把顺序反转过来。

思考题

尝试一下递归的解法!

参考资料

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

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
 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
30
/**
 * Runtime: 1 ms, faster than 86.28% of Java online submissions for Binary Tree Level Order Traversal II.
 * Memory Usage: 38.8 MB, less than 5.00% of Java online submissions for Binary Tree Level Order Traversal II.
 */
public List<List<Integer>> levelOrderBottom(TreeNode root) {
    if (Objects.isNull(root)) {
        return Collections.emptyList();
    }
    List<List<Integer>> result = new ArrayList<>();
    Deque<TreeNode> deque = new LinkedList<>();
    deque.addLast(root);
    while (!deque.isEmpty()) {
        int size = deque.size();
        List<Integer> nums = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            TreeNode node = deque.removeFirst();
            nums.add(node.val);
            if (Objects.nonNull(node.left)) {
                deque.addLast(node.left);
            }
            if (Objects.nonNull(node.right)) {
                deque.addLast(node.right);
            }
        }
        result.add(nums);
    }
    Collections.reverse(result);
    return result;
}
 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
/**
 *
 */
public List<List<Integer>> levelOrderBottom(TreeNode root) {
  if (root == null) {
    return Collections.emptyList();
  }
  List<List<Integer>> result = new LinkedList<>();
  Queue<TreeNode> queue = new LinkedList<>();
  queue.offer(root);
  while (!queue.isEmpty()) {
    int size = queue.size();
    List<Integer> level = new ArrayList<>();
    for (int i = 0; i < size; i++) {
      TreeNode node = queue.poll();
      level.add(node.val);
      if (node.left != null) {
        queue.offer(node.left);
      }
      if (node.right != null) {
        queue.offer(node.right);
      }
    }
    result.add(0, level);
  }
  return result;
}

相比第一次解,第二次解直接在链表前面添加元素即可,这样就无需反转了。