二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

思路

其实就是在在层次遍历的基础进行修改,判断是否是偶数层,如果是,就进行反转

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        
        List<List<Integer>> L=new ArrayList<List<Integer>>();
        if(root==null){
            return L;
        }
        Queue<TreeNode> q=new LinkedList<TreeNode>();
        q.offer(root);
        int count=1;
        
        while(!q.isEmpty()){
            
            List<Integer> list=new ArrayList<Integer>();
            int size=q.size();
            for(int i=0;i<size;++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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容