按之字形顺序打印二叉树
描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
该二叉树之字形层序遍历的结果是
[
[1],
[3,2],
[4,5]
]
示例1
输入:
{1,2,3,#,#,4,5}
返回值:
[[1],[3,2],[4,5]]
开始我是这样写的,
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
if (pRoot==null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);
//false奇数行,true偶数行
boolean flag = false;
while (queue.isEmpty()==false) {
ArrayList<Integer> temp = new ArrayList<>();
int size = queue.size();
while (size--!=0) {
TreeNode poll = queue.poll();
temp.add(poll.val);
if (flag==false) {
if (poll.right!=null) {
queue.offer(poll.right);
}
if (poll.left!=null) {
queue.offer(poll.left);
}
}
if (flag==true) {
if (poll.left!=null) {
queue.offer(poll.left);
}
if (poll.right!=null) {
queue.offer(poll.right);
}
}
}
result.add(temp);
flag=!flag;
}
return result;
}
用例输入:{8,6,10,5,7,9,11}
预期输出:[[8],[10,6],[5,7,9,11]]
实际输出:[[8],[10,6],[9,11,5,7]]
后来看了答案,其实我是想复杂了,下面是ac代码:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
if (pRoot==null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);
//false奇数行,true偶数行
boolean flag = false;
while (queue.isEmpty()==false) {
ArrayList<Integer> temp = new ArrayList<>();
int size = queue.size();
while (size--!=0) {
TreeNode poll = queue.poll();
temp.add(poll.val);
if (poll.left!=null) {
queue.offer(poll.left);
}
if (poll.right!=null) {
queue.offer(poll.right);
}
}
ArrayList<Integer> reverseList = new ArrayList<>();
if (flag==true) {
for (int i = temp.size()-1; i >= 0; i--) {
reverseList.add(temp.get(i));
}
}
if (flag==false) {
result.add(temp);
} else {
result.add(reverseList);
}
flag=!flag;
}
return result;
}
}
欢迎留言~