其他分享
首页 > 其他分享> > 2022-7-2 剑指offer-二叉树-层序遍历变种

2022-7-2 剑指offer-二叉树-层序遍历变种

作者:互联网

剑指 Offer 32 - III. 从上到下打印二叉树 III

难度中等

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public List<List<Integer>> levelOrder(TreeNode root) {
12         
13         if (root==null) return new ArrayList<>();
14         Queue<TreeNode> queue=new LinkedList<>();
15         queue.offer(root);
16         List<List<Integer>> ans=new ArrayList<>();
17         boolean flag=false;
18         while (!queue.isEmpty()){
19             int len=queue.size();
20             List<Integer> list=new ArrayList<>();
21             for (int i=0;i<len;i++){
22                 TreeNode temp=queue.poll();
23                 list.add(temp.val);
24                 if (temp.left!=null) queue.offer(temp.left);
25                 if (temp.right!=null) queue.offer(temp.right);
26 
27             }
28             if (flag) Collections.reverse(list);
29             ans.add(list);
30             flag=!flag;
31         }
32         return ans;
33     }
34 }

思路:层序遍历的基础上判断是否要反转列表。

标签:打印,TreeNode,offer,int,层序,queue,二叉树,new
来源: https://www.cnblogs.com/benbicao/p/16437037.html