问题描述:
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] ]
原问题链接:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
问题分析
这个问题是前一个问题的简单变化。我们只要知道了树的层次化遍历的方法,这个问题也就很容易解决了。这里只是每一层遍历的时候是按照之字形的去遍历。这样我们可以定义一个boolean left值来表示是否先从左边往右来遍历。我们每遍历完一层之后就将这个值设为原来相反的值。同时,根据left是否为true来返回结果,如果为true,则直接返回当前遍历得到的值,否则将当前的值列表倒置一下在加入到结果中。
详细的代码实现如下:
/** * 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>> result = new ArrayList<>(); if(root == null) return result; boolean left = true; List<TreeNode> list = new ArrayList<>(); list.add(root); while(!list.isEmpty()) { List<Integer> intList = new ArrayList<>(); List<TreeNode>temp = new ArrayList<>(); for(TreeNode node : list) { intList.add(node.val); if(node.left != null) temp.add(node.left); if(node.right != null) temp.add(node.right); } if(!left) Collections.reverse(intList); result.add(intList); left = !left; list = temp; } return result; } }
相关推荐
python python_leetcode题解之103_Binary_Tree_Zigzag_Level_Order_Traversal
js js_leetcode题解之103-binary-tree-zigzag-level-order-traversal.js
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
103 Binary Tree Zigzag Level Order Traversal.js(二叉树之字形级别顺序Traversal.js) 104 Binary Tree.js的最大深度 105从Preorder和Inorder Traversal.js构造二叉树 106从有序和后置Traversal.js构造二叉树 ...
java lru leetcode what_the_dead_men_say 所以这只是一个 repo,我从leetcode.com存储我的...Zigzag Level Order Traversal - Python3 iterative BFS w Deques 0104 Maximum depth of binary tree - Java Iterative
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. ...
[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-...
* [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]...
7. 题目107 - "Binary Tree Level Order Traversal II" 本题要求对二叉树进行倒序层次遍历。Java中,可以使用队列进行层次遍历,但每次取出节点后,先将其子节点加入队列,最后再处理该节点,以达到倒序的效果。 ...