这个提跟Binary Tree Level Order Traversal 一样,只是结果集用栈
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root == null){ return result; } List<Integer> first = new ArrayList<Integer>(); first.add(root.val); result.add(first); LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); LinkedList<TreeNode> childrenQueue = new LinkedList<TreeNode>(); queue.add(root); int i =1; while (!queue.isEmpty()) { TreeNode node = queue.remove(); if(node.left!=null){ childrenQueue.add(node.left); } if(node.right!=null){ childrenQueue.add(node.right); } if(queue.isEmpty() && !childrenQueue.isEmpty()){ queue.addAll(childrenQueue); LinkedList<Integer> childrenResult = new LinkedList<Integer>(); boolean flag = i%2==0?true:false; for(TreeNode child : childrenQueue){ if(flag){ childrenResult.add(child.val); }else{ childrenResult.push(child.val); } } result.add(childrenResult); childrenQueue.clear(); i++; } } return result; } }
相关推荐
js js_leetcode题解之103-binary-tree-zigzag-level-order-traversal.js
python python_leetcode题解之103_Binary_Tree_Zigzag_Level_Order_Traversal
java lru leetcode what_the_dead_men_say 所以这只是一个 repo,我从leetcode.com存储我的问题解决方案。 二叉树 0098 Validate Binary Search Tree - Java Recursive - Java Iterative - Java Inorder 0099 ...
lru缓存leetcode 1 https://leetcode.com/problems/two-sum/ Two ...https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Binary Tree Zigzag Level Order Traversal 104 htt
Javascript 的解决方案Leetcode Problems and interview problems in Javascript10 Regular Expresion Matching.js100 Same Tree.js101 Symmetric Tree.js102 Binary Tree Level Order Traversal.js103 Binary Tree ...
lru缓存leetcode LeetCode_Note leetcode 个人笔记 问题清单 [1_two_sum.cpp] [10_regular-expression-matching.cpp] [100_same-tree.cpp] ...[107_binary-tree-level-order-traversal-ii.cpp] [108_convert-sorted
103 Binary Tree Zigzag Level Order Traversal.js(二叉树之字形级别顺序Traversal.js) 104 Binary Tree.js的最大深度 105从Preorder和Inorder Traversal.js构造二叉树 106从有序和后置Traversal.js构造二叉树 ...
* [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...
PYTHONhttps://github.com/meetpatel1311/LeetCode/blob/main/Python/103_Binary_Tree_Zigzag_Level_Order_Traversal.py 力扣问题 数字 标题 解决方案 1. 2. 3. 4. 5. 6. 7. 8. 9. 11. 12. 13. 14. 15. 16. 17. 19. ...
7. 题目107 - "Binary Tree Level Order Traversal II" 本题要求对二叉树进行倒序层次遍历。Java中,可以使用队列进行层次遍历,但每次取出节点后,先将其子节点加入队列,最后再处理该节点,以达到倒序的效果。 ...