zoukankan      html  css  js  c++  java
  • 102. Binary Tree Level Order Traversal Java Solutions

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

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

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    Subscribe to see which companies asked this question

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<List<Integer>> levelOrder(TreeNode root) {
    12         List<List<Integer>> res = new ArrayList<List<Integer>>();
    13         Queue<TreeNode> q = new LinkedList<TreeNode>();
    14         if(root == null) return res;
    15         q.add(root);
    16         while(!q.isEmpty()){
    17             List<Integer> tmp = new ArrayList<Integer>();
    18             int size = q.size();
    19             for(int i = 0; i< size; i++){
    20                 TreeNode node = q.poll();
    21                 tmp.add(node.val);
    22                 if(node.left != null) q.add(node.left);
    23                 if(node.right != null) q.add(node.right);
    24             }
    25             res.add(tmp);
    26             
    27         }
    28         return res;
    29     }
    30 }

    java 中queue 的操作:

    add    增加一个元索                     如果队列已满,则抛出一个IIIegaISlabEepeplian异常
    remove   移除并返回队列头部的元素    如果队列为空,则抛出一个NoSuchElementException异常
    element  返回队列头部的元素             如果队列为空,则抛出一个NoSuchElementException异常
    offer       添加一个元素并返回true       如果队列已满,则返回false
    poll         移除并返问队列头部的元素    如果队列为空,则返回null
    peek       返回队列头部的元素             如果队列为空,则返回null
    put         添加一个元素                      如果队列满,则阻塞
    take        移除并返回队列头部的元素     如果队列为空,则阻

  • 相关阅读:
    电脑知识
    编译器错误信息: CS0433: 类型“ASP.global_asax”同时存在于“c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727...的解决方法
    windows平台下的oracle ORA-01031的解决方法
    .NET下使用HTTP请求的正确姿势
    EasyUI Datagrid 分页
    Js 运算符(加减乘除)
    Navicat 运行 Oracle 存储过程示例
    oracle数据库忘记sys(或system)账户密码
    SQL Server 死锁问题
    C# 给某个方法设定执行超时时间
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5452617.html
Copyright © 2011-2022 走看看