/**
* 给定一个二叉树,返回该二叉树由底层到顶层的层序遍历,(从左向右,从叶子节点到根节点,一层一层的遍历)
* 例如:
* 给定的二叉树是{3,9,20,#,#,15,7},
* 3↵ / ↵ 9 20↵ / ↵ 15 7
* 该二叉树由底层到顶层层序遍历的结果是
* [↵ [15,7]↵ [9,20],↵ [3],↵]
*
*/
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* 给定一个二叉树,返回该二叉树由底层到顶层的层序遍历,(从左向右,从叶子节点到根节点,一层一层的遍历)
* 例如:
* 给定的二叉树是{3,9,20,#,#,15,7},
* 3↵ / ↵ 9 20↵ / ↵ 15 7
* 该二叉树由底层到顶层层序遍历的结果是
* [↵ [15,7]↵ [9,20],↵ [3],↵]
*
*/
public class Main50 {
public static void main(String[] args) {
// TreeNode root = null;
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
System.out.println(Main50.levelOrderBottom(root));
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
ArrayList<TreeNode> array = new ArrayList<>();
if (root == null) {
return list;
}
TreeNode head = root;
array.add(head);
while (!array.isEmpty()) {
ArrayList<TreeNode> newArray = new ArrayList<>();
ArrayList<Integer> subList = new ArrayList<>();
for (TreeNode t : array) {
if (t.left != null) {
newArray.add(t.left);
}
if (t.right != null) {
newArray.add(t.right);
}
subList.add(t.val);
}
array = newArray;
list.add(0,subList);
}
return list;
}
}