zoukankan      html  css  js  c++  java
  • leecode 103. 二叉树的锯齿形层序遍历

    import java.util.ArrayDeque;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Queue;
    
    public class lc103 {
    
        public class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
            TreeNode(int x) { val = x; }
        }
    
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            if(root==null) return res;
            Queue<TreeNode> q = new ArrayDeque();
            q.add(root);
            boolean flag = true;
            while(!q.isEmpty()){
                int size = q.size();
                List<Integer> ls = new ArrayList<>();
                while(size>0){
                    TreeNode temp = q.remove();
                    if(flag) ls.add(temp.val);
                    else ls.add(0,temp.val);    //在头部添加
                    if(temp.left!=null) q.add(temp.left);
                    if(temp.right!=null) q.add(temp.right);
                    size--;
                }
                res.add(ls);
                flag = !flag;
            }
            return res;
        }
    }
  • 相关阅读:
    CCF CSP 201403-2 窗口
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
    Ethical Hacking
  • 原文地址:https://www.cnblogs.com/kpwong/p/14657795.html
Copyright © 2011-2022 走看看