103:二叉树的锯齿形层序遍历
This commit is contained in:
parent
33abfefdf9
commit
f6ebc8cef4
@ -27,10 +27,7 @@ package leetcode.editor.cn;
|
||||
|
||||
import com.code.leet.entiy.TreeNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
import java.util.*;
|
||||
|
||||
//103:二叉树的锯齿形层序遍历
|
||||
public class BinaryTreeZigzagLevelOrderTraversal {
|
||||
@ -59,40 +56,37 @@ public class BinaryTreeZigzagLevelOrderTraversal {
|
||||
* }
|
||||
*/
|
||||
class Solution {
|
||||
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
|
||||
List<List<Integer>> result = new ArrayList<>();
|
||||
Stack<TreeNode> stack1 = new Stack<>();
|
||||
Stack<TreeNode> stack2 = new Stack<>();
|
||||
stack1.push(root);
|
||||
TreeNode temp;
|
||||
List<Integer> list;
|
||||
while (!stack1.isEmpty() || !stack2.isEmpty()) {
|
||||
list = new ArrayList<>();
|
||||
while (!stack1.isEmpty()) {
|
||||
temp = stack1.pop();
|
||||
list.add(temp.val);
|
||||
if (temp.left != null) {
|
||||
stack2.push(temp.left);
|
||||
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {List<List<Integer>> ans = new LinkedList<List<Integer>>();
|
||||
if (root == null) {
|
||||
return ans;
|
||||
}
|
||||
if (temp.right != null) {
|
||||
stack2.push(temp.right);
|
||||
|
||||
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
|
||||
nodeQueue.offer(root);
|
||||
boolean isOrderLeft = true;
|
||||
|
||||
while (!nodeQueue.isEmpty()) {
|
||||
Deque<Integer> levelList = new LinkedList<Integer>();
|
||||
int size = nodeQueue.size();
|
||||
for (int i = 0; i < size; ++i) {
|
||||
TreeNode curNode = nodeQueue.poll();
|
||||
if (isOrderLeft) {
|
||||
levelList.offerLast(curNode.val);
|
||||
} else {
|
||||
levelList.offerFirst(curNode.val);
|
||||
}
|
||||
result.add(list);
|
||||
if (curNode.left != null) {
|
||||
nodeQueue.offer(curNode.left);
|
||||
}
|
||||
list = new ArrayList<>();
|
||||
while (!stack2.isEmpty()) {
|
||||
temp = stack2.pop();
|
||||
list.add(temp.val);
|
||||
if (temp.right != null) {
|
||||
stack1.push(temp.right);
|
||||
}
|
||||
if (temp.left != null) {
|
||||
stack1.push(temp.left);
|
||||
}
|
||||
result.add(list);
|
||||
if (curNode.right != null) {
|
||||
nodeQueue.offer(curNode.right);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
ans.add(new LinkedList<Integer>(levelList));
|
||||
isOrderLeft = !isOrderLeft;
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
|
Loading…
Reference in New Issue
Block a user