前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
一开始以为还是用两个队列,只是插入的顺序不一样,后来仔细想想,原来是用堆。。Your runtime beats 10.01% of java submissions.
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
if(root != null){
stack1.push(root);
while(!stack1.empty() || !stack2.empty()){
if(!stack1.empty()){
List<Integer> result = new ArrayList<Integer>();
while(!stack1.empty()){
TreeNode node = stack1.pop();
result.add(node.val);
if(node.left != null) stack2.push(node.left);
if(node.right != null) stack2.push(node.right);
}
results.add(result);
}
if(!stack2.empty()){
List<Integer> result = new ArrayList<Integer>();
while(!stack2.empty()){
TreeNode node = stack2.pop();
result.add(node.val);
if(node.right != null) stack1.push(node.right);
if(node.left != null) stack1.push(node.left);
}
results.add(result);
}
}
}
return results;
}
}
本文介绍了一种解决二叉树锯齿形层序遍历问题的算法,通过使用两个栈来实现从左到右再从右到左的交替遍历方式,并附带了完整的Java代码实现。
9771

被折叠的 条评论
为什么被折叠?



