zoukankan      html  css  js  c++  java
  • leetcode之Binary Tree Level Order Traversal

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

    这道题的意思是树的层序遍历,
    用到了队列,每打印一个节点的时候,如果这个结点有左右子树,则将其左右子树加入队列。
    由于输出的形式是每一层相当于list中的一个元素,因此在程序中每一层都用到了for循环,
    貌似图的广度优先也是用的队列
    代码如下:
    public List<List<Integer>> levelOrder(TreeNode root) {
            ArrayList result = new ArrayList();
    		if(root==null){
    			return result;
    		}
    		Queue<TreeNode> q = new LinkedList<TreeNode>();
    		q.offer(root);
    		while(!q.isEmpty()){
    			ArrayList<Integer> lever = new ArrayList<Integer>();
    			int size = q.size();
    			for(int i = 0;i<size;i++){
    				TreeNode temp = q.poll();
    				lever.add(temp.val);
    				if(temp.left!=null){
    					q.offer(temp.left);
    				}
    				if(temp.right!=null){
    					q.offer(temp.right);
    				}
    			}
    			result.add(lever);
    		}
    		return result;
        }
    

      队列的方法有如下几种:

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

  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4575872.html
Copyright © 2011-2022 走看看