0
点赞
收藏
分享

微信扫一扫

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

吓死我了_1799 2022-02-16 阅读 41

题目:

分析:

深度遍历这棵树,然后判断当前层数,若为偶数层,该list反转。 

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list =new ArrayList();
        Queue<TreeNode> q=new LinkedList();
        int i=1;
        q.offer(root);
        q.offer(null);
        while(q.peek()!=null){
             List<Integer> l=new ArrayList();
             list.add(l);
             while(q.peek()!=null){
                 TreeNode t=q.poll();
                 if(t.left!=null){
                    q.offer(t.left);
                 }
                 if(t.right!=null){
                    q.offer(t.right);
                 }
                 l.add(t.val);
             }
             q.remove();
             q.offer(null);
             if(i%2==0){
                 Collections.reverse(l);
             }
             i++;
        }
        return list;
    }
}
举报

相关推荐

0 条评论