Advertisement
sweet1cris

Untitled

Jan 9th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. /**
  2.  * Definition of TreeNode:
  3.  * public class TreeNode {
  4.  *     public int val;
  5.  *     public TreeNode left, right;
  6.  *     public TreeNode(int val) {
  7.  *         this.val = val;
  8.  *         this.left = this.right = null;
  9.  *     }
  10.  * }
  11.  */
  12. public class Solution {
  13.     /**
  14.      * @param root: The root of binary tree.
  15.      * @return: buttom-up level order a list of lists of integer
  16.      */
  17.     public List<List<Integer>> levelOrderBottom(TreeNode root) {
  18.         List<List<Integer>> result = new ArrayList<>();
  19.         if (root == null) {
  20.             return result;
  21.         }
  22.         Queue<TreeNode> queue = new LinkedList<TreeNode>();
  23.         queue.offer(root);
  24.        
  25.         while (!queue.isEmpty()) {
  26.             int size = queue.size();
  27.             List<Integer> level = new ArrayList<>();
  28.             for (int i = 0; i < size; i++) {
  29.                 TreeNode head = queue.poll();
  30.                 level.add(head.val);
  31.                 if (head.left != null) {
  32.                     queue.offer(head.left);
  33.                 }
  34.                 if (head.right != null) {
  35.                     queue.offer(head.right);
  36.                 }
  37.             }
  38.             result.add(level);
  39.         }
  40.        
  41.         Collections.reverse(result);
  42.         return result;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement