题目
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
样例
思路分析
step1: 标准的层序遍历,并且打印每一行数据
step2:增加一个变量来记录层数levelNum = 1 如果levelNum % 2 == 1 那么说明不需要逆序,结果=0 将数据逆序即可
代码
package 剑指offer.搜索与回溯.offer32C;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
TreeNode tree = new Solution.TreeNode();
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
TreeNode() {
}
}
public static void main(String[] args) {
Solution solution = new Solution();
Integer[] test = {1,2,3,4,5,6,7};
solution.buildTree(test);
List<List<Integer>> lists = solution.levelOrder(solution.tree);
System.out.println(lists);
}
public void buildTree(Integer[] treeNode){
LinkedList<TreeNode> treeNodes = new LinkedList<>();
treeNodes = new LinkedList<>();
int size = treeNode.length;
int index = 0;
tree.val = treeNode[index];
treeNodes.offer(tree);
while (!treeNodes.isEmpty()){
int val = treeNode[index];
if(++index >=size){
break;
}
int leftVal = treeNode[index];
if(++index >=size){
break;
}
int rightVal = treeNode[index];
TreeNode peek = treeNodes.peek();
peek.left = new TreeNode(leftVal);
peek.right = new TreeNode(rightVal);
treeNodes.offer(peek.left);
treeNodes.offer(peek.right);
treeNodes.poll();
}
}
/**
* 思路分析:
* step1:采用层序遍历的方式来完成
* 1. 定一个queue来存放节点
*
*
* step2:在层序遍历的基础上,对于队列长度进行判断,增加一个for循环来打印每一层的
* step3:增加一个变量levelNum=1来标记层数,levelNum %2 ==1 那么从左向右 ==0从右向左List需要转置
* @param root
* @return
*/
public List<List<Integer>> levelOrder(TreeNode root) {
List<Integer> levelRes = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
int levelNum = 1;
//todo:root为null单独判断
if(root==null){
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
//对于每一层进行处理
int size = queue.size();
levelRes = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode peek = queue.peek();
int val = peek.val;
TreeNode left = peek.left;
TreeNode right = peek.right;
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}
queue.poll();
//实现该功能部分
if(levelNum % 2 == 1) {
levelRes.add(val);
}else{
levelRes.add(0,val);
}
}
levelNum++;
res.add(levelRes);
}
return res;
}
}