算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 二叉树的锯齿形层次遍历,我们先来看题面:
https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
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).
题意
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 样例解题
本题有很多解法,不过今天我想要分享一种更简单的方法:就是在在层次遍历的基础进行修改,判断是否是偶数层,如果是,就进行反转 ,代码如下:
class Solution {public List<List> zigzagLevelOrder(TreeNode root) {List<List> L=new ArrayList<List>();if(root==null){return L;
}
Queue q=new LinkedList();
q.offer(root);
int count=1;while(!q.isEmpty()){Listlist=new ArrayList();
int size=q.size();for(int i=0;i TreeNode temp=q.poll();if(temp.left!=null){
q.offer(temp.left);
}if(temp.right!=null){
q.offer(temp.right);
}list.add(temp.val);
}if(count%2!=0){
L.add(list);
}else{
Collections.reverse(list);
L.add(list);
}
count++;
}return L;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。
上期推文:
LeetCode1-100题汇总,希望对你有点帮助!LeetCode刷题实战101:对称二叉树 LeetCode刷题实战102:二叉树的层序遍历