从上到下打印二叉树
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回
[3,9,20,15,7]
提示:
节点总数 <= 1000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] levelOrder(TreeNode root) {
if(root == null){
return new int[0];
}
List<Integer> list = new ArrayList();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
list.add(root.val);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(null != node.left){
list.add(node.left.val);
queue.add(node.left);
}
if(null != node.right){
list.add(node.right.val);
queue.add(node.right);
}
}
int length = list.size();
int[] arr = new int[length];
for (int i = 0; i < length; i++){
arr[i] = list.get(i);
}
return arr;
}
}
从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(null == root){
return new ArrayList();
}
List<List<Integer>> resultList = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
List<TreeNode> tempList = new ArrayList();
List<Integer> valList = new ArrayList();
while(!queue.isEmpty()){
TreeNode node = queue.poll();
valList.add(node.val);
if(null != node.left){
tempList.add(node.left);
}
if(null != node.right){
tempList.add(node.right);
}
}
queue.addAll(tempList);
resultList.add(valList);
}
return resultList;
}
}
从上到下打印二叉树 III
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
提示:
节点总数 <= 1000
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(null == root){
return new ArrayList();
}
List<List<Integer>> resultList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
boolean flag = true;
while(!stack.isEmpty()){
List<TreeNode> tempList = new ArrayList();
List<Integer> valList = new ArrayList();
while(!stack.isEmpty()){
TreeNode node = stack.pop();
valList.add(node.val);
if(flag){
if(null != node.left){
tempList.add(node.left);
}
if(null != node.right){
tempList.add(node.right);
}
}else {
if(null != node.right){
tempList.add(node.right);
}
if(null != node.left){
tempList.add(node.left);
}
}
}
stack.addAll(tempList);
resultList.add(valList);
flag = !flag;
}
return resultList;
}
}