菜鸡每日一题系列打卡103天
每天一道算法题目
小伙伴们一起留言打卡
坚持就是胜利,我们一起努力!
题目描述(引自LeetCode)
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3/ \9 20/ \15 7
返回锯齿形层次遍历如下:
[[3],[20,9],[15,7]]
题目分析
这是每日一题——二叉树的层序遍历题目的变型,题目中描述的锯齿形层次遍历也就是我们常说的zigzag。只要稍加思考就会发现,其实这两道题目并无本质上的区别,只需要调整一下偶数层的排列顺序即可。
基于以上分析,我们仍然可以采用递归或迭代的方式进行求解,并针对level的奇偶做不同处理。为了给大家提供不同的思路,菜鸡在本文中将采用上述两种方式进行解答。话不多说,上代码!
代码实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
// 递归class Solution {private List<List<Integer>> result = new ArrayList<>();public List<List<Integer>> zigzagLevelOrder(TreeNode root) {zigzag(root, 0);return result;}private void zigzag(TreeNode root, int level) {if (root == null) return;if (result.size() == level) result.add(new ArrayList<>());if ((level & 1) == 1) result.get(level).add(0, root.val);else result.get(level).add(root.val);zigzag(root.left, level + 1);zigzag(root.right, level + 1);}}
// 迭代class Solution {public List<List<Integer>> zigzagLevelOrder(TreeNode root) {if (root == null) return new ArrayList<>();List<List<Integer>> result = new LinkedList<>();LinkedList<TreeNode> queue = new LinkedList<>();queue.offer(root);int level = 1;while (!queue.isEmpty()) {int size = queue.size();LinkedList<Integer> tmp = new LinkedList<>();while (size-- > 0) {TreeNode current = queue.poll();if (current.left != null) queue.offer(current.left);if (current.right != null) queue.offer(current.right);if ((level & 1) == 1) tmp.add(current.val);else tmp.push(current.val);}level++;result.add(tmp);}return result;}}
代码分析
对代码进行分析,不妨设二叉树的结点个数为n,则:
递归:时间复杂度为O(n),空间复杂度为O(n)。
迭代:时间复杂度为O(n),空间复杂度为O(n)。
执行结果

递归的执行结果

迭代的执行结果
福利抽奖👇

学习 | 工作 | 分享

👆长按关注“有理想的菜鸡”
文章转载自有理想的菜鸡,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




