zoukankan      html  css  js  c++  java
  • Java for LeetCode 103 Binary Tree Zigzag Level Order Traversal

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its zigzag level order traversal as:

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

    解题思路:

    直接在上题加一条反转语句即可,JAVA实现如下:

        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<List<Integer>>();
    		if (root == null)
    			return list;
    		Queue<TreeNode> queue = new LinkedList<TreeNode>();
    		queue.add(root);
    		while (queue.size() != 0) {
    			List<Integer> alist = new ArrayList<Integer>();
    			for (TreeNode child : queue)
    				alist.add(child.val);
    			if(list.size()%2!=0)
    				Collections.reverse(alist);
    			list.add(new ArrayList<Integer>(alist));
    			Queue<TreeNode> queue2 = queue;
    			queue = new LinkedList<TreeNode>();
    			for (TreeNode child : queue2) {
    				if (child.left != null)
    					queue.add(child.left);
    				if (child.right != null)
    					queue.add(child.right);
    			}
    		}
    		return list;
        }
    
  • 相关阅读:
    02-最简C语言程序
    Go学习笔记-GO编程语言手册
    Go学习笔记-Effective Go
    go学习笔记-语法
    机器学习-数据挖掘
    windows下jupyter notebook的安装及配置
    wpf学习笔记
    windows下安装mingW及控制台启用
    nginx
    MFC学习笔记
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4523693.html
Copyright © 2011-2022 走看看