跳转至

107. Binary Tree Level Order Traversal II

Leetcode Tree Breath-first Search

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]
]

分析

这道题目是LeeCode 102. Binary Tree Level Order Traversal的扩展,唯一的区别是这道题目要求从底向上的遍历。所以非常直接的方法就是把LeetCode102的结果反转一下:

public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> levels = new ArrayList<List<Integer>>();
    if (root == null) return levels;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        List<Integer> curLevel = new ArrayList<>();
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
            curLevel.add(node.val);
        }
        levels.add(curLevel);
    }
    Collections.reverse(levels);
    return levels;    
}

或者使用链表,每次添加在链表首部

public List<List<Integer>> levelOrderBottom(TreeNode root) {
    LinkedList<List<Integer>> levels = new LinkedList<List<Integer>>();
    if (root == null) return levels;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        List<Integer> curLevel = new ArrayList<>();
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
            curLevel.add(node.val);
        }
        levels.addFirst(curLevel);
    }

    return levels;
}