题解 | #牛群Z字型排列#
牛群Z字型排列
https://www.nowcoder.com/practice/50ddaf50c6954600a9f1dbb099d6f388?tpId=354&tqId=10591743&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型二维数组 */ public int[][] ZLevelOrder (TreeNode root) { // write code here Deque<TreeNode> outer = new LinkedList<>(); Deque<TreeNode> inner = new LinkedList<>(); if(root != null) outer.offerFirst(root); List<int[]> list = new ArrayList<>(); int flag = 1; //左右标志 while (!outer.isEmpty()){ int[] arr = new int[outer.size()]; while(!outer.isEmpty()){ inner.offerFirst(outer.pollFirst()); } flag ++; int i = 0; while(!inner.isEmpty()){ TreeNode treeNode = inner.pollLast(); arr[i++] = treeNode.val; if(flag % 2 == 0){ if(treeNode.left != null) outer.offerFirst(treeNode.left); if(treeNode.right != null) outer.offerFirst(treeNode.right); } else { if(treeNode.right != null) outer.offerFirst(treeNode.right); if(treeNode.left != null) outer.offerFirst(treeNode.left); } } list.add(arr); } return list.toArray(new int[list.size()][]); } }
知识点:
树,层序遍历
解题思路:
还是层序遍历放入队列中,取出每层队列。
只不过和上题不同的是层序外层时,取出是从顶部取出,也就是poffFist,还有在放入时需要加入一个flag标志,判断先放左子树还是右子树。