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


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

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

    例如:
    给定二叉树: [3,9,20,null,null,15,7],

    3
    

    /
    9 20
    /
    15 7
    返回其层次遍历结果:

    [
    [3],
    [20,9],
    [15,7]
    ]

    提示:

    节点总数 <= 1000

    /**
     * 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) {
                if(root==null) return new  LinkedList<List<Integer>>();
                Queue<TreeNode> que = new LinkedList<>();
                List<List<Integer>> res = new ArrayList<>();
                que.add(root);
                int i = 0;
                while(!que.isEmpty())
                {
                    int num =  que.size();
                    List<Integer>  re = new ArrayList<>();
                    while(num-->0)
                    {
                        TreeNode node = que.poll();
                        System.out.println(node);
                        if(node.left!=null)
                        que.add(node.left);
                        if(node.right!=null)
                        que.add(node.right);
                        re.add(node.val);
                    }
                    if (i%2!=0) {
                        Collections.reverse(re);
                    }
                    i++;
                    res.add(re);
                }
                return  res;
    
    
    
    
            }
    }
    
  • 相关阅读:
    ZOJ3213-Beautiful Meadow
    ZOJ3256-Tour in the Castle
    ZOJ3466-The Hive II
    hdu3377-Plan
    fzu1977-Pandora Adventure
    ural1519-Formula 1
    poj2914-Minimum Cut
    51nod-1220-约数之和
    51nod-1222-最小公倍数计数
    【html】【6】div浮动float
  • 原文地址:https://www.cnblogs.com/shenxiaodou/p/16026180.html
Copyright © 2020-2023  润新知