• 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]
    ]

    这道题主要用BFS解决,在BFS得到结果后需要考虑是否要逆序一下。逆序可以考虑用栈,我没有用栈,直接逆序
    public class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();			//保存最后的结果
            if(null == root)
            	return result;
            boolean needReverse = false;												//是否要对列表中的内容进行逆序
            Queue<TreeNode> queue = new LinkedList<TreeNode>();						//BFS要使用到的队列
            queue.add(root);														//根节点入队
            while(!queue.isEmpty()){												//队列不为空
            	List<Integer> oneLevel = new ArrayList<Integer>();					//保存在同一层及节点的值
            	Queue<TreeNode> temp = new LinkedList<TreeNode>();					//存放下一层的节点
            	while(!queue.isEmpty()){
            		TreeNode headOfQueue = queue.remove();							//对头元素出队
            		oneLevel.add(headOfQueue.val);
            		if(headOfQueue.left != null)
            			temp.add(headOfQueue.left);									//左子树不为空,入队
            		if(headOfQueue.right != null)
            			temp.add(headOfQueue.right);								//右子树不为空,入队
            	}//while
            	if(needReverse)
            		reverseList(oneLevel);
            	result.add(oneLevel);
            	needReverse = !needReverse;
            	queue = temp;
            }
            return result;
        }
        
        /**
         * list列表中内容逆序
         * @param list
         */
        private void reverseList(List<Integer> list){
        	for(int i = 0, j = list.size() - 1; i < j; i++, j--){
        		int temp = list.get(i);
        		list.set(i, list.get(j));
        		list.set(j, temp);
        	}
        }
    }
    

      



  • 相关阅读:
    201119西瓜书系列博客---5、神经网络
    GO结果画图
    Java调用R语言脚本
    CentOS 6,7 查看、修改时间时区
    eval 让shell脚本动态的构建命令
    shell脚本中awk命令内置参数与脚本参数冲突的解决方法
    Shell 传递参数
    clusterProfiler::enrichGO() is getting very slow
    R install("curl") on CentOS 7.6
    centos 7 安装 myclipse 2017 ci
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4194322.html
Copyright © 2020-2023  润新知