[LeetCode 107] Binary Tree Level Order Traversal II (easy)

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

Solution: BFS

  1. 与Binary Tree Level Order Traversal I区别就是,该题是的结果从leaves到root这个顺序;
  2. 只需要用Deque,每次加的时候addFirst即可。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> levelOrderBottom(TreeNode root) {
        Deque> result = new LinkedList<> ();
        if (root == null) {
            return new ArrayList (result);
        }
                
        Queue current = new LinkedList<> ();
        Queue nextLayer = new LinkedList<> ();
        current.offer  (root);
        
        List temp = new ArrayList<> ();
        
        while (!current.isEmpty ()) {
            TreeNode currentNode = current.poll ();
            temp.add (currentNode.val);
            
            if (currentNode.left != null)
                nextLayer.offer (currentNode.left);
            if (currentNode.right != null)
                nextLayer.offer (currentNode.right);
            
            if (current.isEmpty ()) {
                result.addFirst (temp);
                current = nextLayer;
                nextLayer = new LinkedList <>();
                
                temp = new ArrayList<> ();
            }
        }
        
        return new ArrayList (result);
    }
}

你可能感兴趣的:([LeetCode 107] Binary Tree Level Order Traversal II (easy))