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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/** * Definition for a binary tree node. * 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>> res = new ArrayList<List<Integer>>(); if (root == null) { return res; } LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); Boolean reverse = false; int cur = 1; int next = 0; ArrayList<Integer> levelres = new ArrayList<Integer>(); while (!queue.isEmpty()) { TreeNode poll = queue.poll(); cur--; levelres.add(poll.val); if (poll.left != null) { queue.add(poll.left); next++; } if (poll.right != null) { queue.add(poll.right); next++; } if (cur == 0) { cur = next; next = 0; if (reverse) { Collections.reverse(levelres); } reverse = !reverse; res.add(levelres); levelres = new ArrayList<Integer>(); } } return res; } }
相关推荐
lru缓存leetcode 1 ...Two Sum 10 ...Regular Expression Matching ...Tree ...https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Binary Tree Zigzag Level Order Traversal 104 htt
java lru leetcode what_the_dead_men_say 所以这只是一个 ... 二叉树 0098 ...Zigzag Level Order Traversal - Python3 iterative BFS w Deques 0104 Maximum depth of binary tree - Java Iterative
103 Binary Tree Zigzag Level Order Traversal.js(二叉树之字形级别顺序Traversal.js) 104 Binary Tree.js的最大深度 105从Preorder和Inorder Traversal.js构造二叉树 106从有序和后置Traversal.js构造二叉树 ...
python python_leetcode题解之103_Binary_Tree_Zigzag_Level_Order_Traversal
js js_leetcode题解之103-binary-tree-zigzag-level-order-traversal.js
[103_binary-tree-zigzag-level-order-traversal.cpp] [104_maximum-depth-of-binary-tree.cpp] [105_construct-binary-tree-from-preorder-and-inorder-traversal.cpp] [106_construct-binary-tree-from-inorder-...
16. **之字形打印二叉树**(Zigzag Level Order Traversal) - 知识点:二叉树,队列,方向控制 - 解题思路:类似层次遍历,但在每次层次转换时改变打印方向。 以上就是小象学院刷题班3.2-4.171中涉及的主要知识...
7. 题目107 - "Binary Tree Level Order Traversal II" 本题要求对二叉树进行倒序层次遍历。Java中,可以使用队列进行层次遍历,但每次取出节点后,先将其子节点加入队列,最后再处理该节点,以达到倒序的效果。 ...
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. ...