?LeetCode刷題實(shí)戰(zhàn)103:二叉樹的鋸齒形層次遍歷
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做?二叉樹的鋸齒形層次遍歷,我們先來(lái)看題面:
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).
題意

解題
本題有很多解法,不過(guò)今天我想要分享一種更簡(jiǎn)單的方法:就是在在層次遍歷的基礎(chǔ)進(jìn)行修改,判斷是否是偶數(shù)層,如果是,就進(jìn)行反轉(zhuǎn) ,代碼如下:
class?Solution?{
????public?List<List> zigzagLevelOrder(TreeNode root) {
????????
????????List<List> L=new?ArrayList<List >();
????????if(root==null){
????????????return?L;
????????}
????????Queueq=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;
????}
}
上期推文:
