二叉树之字形层序遍历
二叉树的之字形层序遍历
https://www.nowcoder.com/practice/47e1687126fa461e8a3aff8632aa5559?tpId=196&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) { // write code here ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if (root==null) return res; Queue<TreeNode> queue=new LinkedList<>(); queue.add(root); ArrayList<Integer> list = new ArrayList<>(); int flag=0; while (queue.size()>0){ int len = queue.size(); list= new ArrayList<>(); for (int i=1;i<=len;i++){ TreeNode temp = queue.poll(); list.add(temp.val); if (temp.left!=null){ queue.add(temp.left); //System.out.println(temp.left.val); } if(temp.right!=null) { queue.add(temp.right); //System.out.println(temp.right.val); } } if (flag%2==1) Collections.reverse(list); flag++; res.add(list); } return res; }