public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null) return res; Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while (!q.isEmpty()) { int size = q.size(); ArrayList<Integer> level = new ArrayList<>(); while(size-- > 0) { TreeNode node = q.poll(); level.add(node.val); if(node.left != null) q.add(node.left); if(node.right != null) q.add(node.right); } res.add(level); } return res;}
Recrusive O(n^2)
ArrayList<Integer> res;public ArrayList<Integer> levelOrder (Node root){ res = new ArrayList<>(); int height = BinaryTree.height(root); for (int i = 1; i <= height; i++) { printLevel(root, i); res.add(null); // null for next line } return res;}private void printLevel(Node root, int level) { // Base Cases if (root == null) return; if(level == 1) { res.add(root.val); return; } // recurse for left and right printLevel(root.left, level-1); printLevel(root.right, level-1);}