zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层序遍历

    Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层序遍历

    给一个二叉树的root,返回其节点值从上到下遍历,奇数层从左到右 遍历,偶数层从右到左。

    Input: root = [3,9,20,null,null,15,7]
    Output: [[3],[20,9],[15,7]]
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
         public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            
            List<List<Integer>> ans = new ArrayList<>();
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            if(root ==null){
                return ans;
            }
            queue.add(root);
            while(!queue.isEmpty()){
                List<Integer> arr = new ArrayList<>();
                int length = queue.size();
                for(int i =0;i<length;i++){
                    TreeNode n = queue.poll();
                    if(n.left!=null){
                        queue.add(n.left);
                    }
                    if(n.right!=null){
                        queue.add(n.right);
                    }
                    arr.add(n.val);
                }         
                ans.add(arr);
            }
            int size = ans.size();      
            for(int i =0;i<size;i++){
                if(i%2==1){                
                    Collections.reverse(ans.get(i));               
                }
            }
            return ans;
        }
    }
    

    Tag

    tree BFS

  • 相关阅读:
    巡回赛 -- 简单的拓扑排序
    最简单的拓扑排序
    blockhouses
    部分和问题
    jfinal路由简单解析
    python mysql
    Gradle--ubuntu
    解决ssh登录后闲置时间过长而断开连接
    业界有很多MQ产品
    avalon---qunar ued
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14666562.html
Copyright © 2011-2022 走看看