/**
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
* For example:
* Given binary tree{3,9,20,#,#,15,7},
* 3
* /
* 9 20
* /
* 15 7
* return its level order traversal as:
* [
* [3],
* [9,20],
* [15,7]
* ]
*/
这道题目,主要是我们是否知道树的层次遍历。
/**
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
* For example:
* Given binary tree{3,9,20,#,#,15,7},
* 3
* /
* 9 20
* /
* 15 7
* return its level order traversal as:
* [
* [3],
* [9,20],
* [15,7]
* ]
*/
import java.util.ArrayList;
public class Main37 {
public static void main(String[] args) {
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(Main37.levelOrder(root));
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode (int x){
val = x;
}
}
public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
ArrayList<TreeNode> treeNodes = new ArrayList<>();
if (root == null) {
return list;
}
TreeNode head = null;
treeNodes.add(root);
while(!treeNodes.isEmpty()) {
ArrayList<Integer> array = new ArrayList<>();
ArrayList<TreeNode> newTree = new ArrayList<>();
for (int i=0;i<treeNodes.size();i++) {
head = treeNodes.get(i);
array.add(head.val);
if (head.left != null) {
newTree.add(head.left);
}
if (head.right != null) {
newTree.add(head.right);
}
}
treeNodes = newTree;
list.add(array);
}
return list;
}
}