题目链接
思路1
额外加一个栈来使得访问节点的顺序是逆序的
代码1
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root == null){
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
Queue<TreeNode> queue = new ConcurrentLinkedDeque<>();
stack.add(root);
int layer = 0;
while(!stack.isEmpty()){
int numOfNodes = stack.size();
layer++;
List<Integer> temp = new ArrayList<>();
for(int i = 0; i < numOfNodes; i++){
TreeNode node = stack.pop();
temp.add(node.val);
if(layer % 2 == 1){
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}else{
if(node.right != null){
queue.add(node.right);
}
if(node.left != null){
queue.add(node.left);
}
}
}
stack.addAll(queue);
queue.clear();
result.add(temp);
}
return result;
}
}
思路2
访问结点的顺序不改变,仅改变放入列表的顺序
代码2
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
//第一步先从左边开始打印
boolean leftToRight = true;
while(!queue.isEmpty()) {
int count = queue.size();
List<Integer> level = new ArrayList<>();
for(int i = 0; i < count; i++) {
TreeNode node = queue.poll();
if(leftToRight) {
level.add(node.val);
} else {
//如果是从右边开始打印,每次要把访问的节点值加入到列表的最前面
level.add(0, node.val);
}
//左右子节点如果不为空会被加入到队列中
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
result.add(level);
leftToRight = !leftToRight;
}
return result;
}
}
标签:node,queue,层序,BFS,add,二叉树,new,null,result
From: https://www.cnblogs.com/shixuanliu/p/17044074.html