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

    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]
    ]
     1 /**
     2  * Definition for binary tree
     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>> container = new ArrayList<List<Integer>>();
    13         if(null == root)
    14             return container;
    15         //List<TreeNode> theSameLevel = new ArrayList<TreeNode>();//存放同一层节点
    16         Queue<TreeNode> theSameLevel = new LinkedList<TreeNode>();
    17         theSameLevel.add(root);
    18         while(!theSameLevel.isEmpty()){//theSameLevel不为空
    19             List<Integer> oneLevel = new ArrayList<Integer>();
    20             Queue<TreeNode> temp = new LinkedList<TreeNode>();//暂存同一层的结点
    21             while(!theSameLevel.isEmpty()){
    22                 TreeNode cur = theSameLevel.remove();
    23                 oneLevel.add(cur.val);
    24                 if(null != cur.left) 
    25                     temp.add(cur.left);
    26                 if(null != cur.right)
    27                     temp.add(cur.right);
    28             }
    29             theSameLevel = temp;
    30             container.add(oneLevel);
    31         }
    32         
    33         return container;
    34     }
    35 }
  • 相关阅读:
    gcc数据对齐之: howto 2.
    gcc数据对齐之: howto 1.
    gcc数据结构对齐之:why.
    linux tricks 之 BUILD_BUG_ON_ZERO.
    linux tricks 之 FIELD_SIZEOF.
    linux tricks 之 container_of.
    linux tricks 之 bitmap分析.
    linux tricks 之 roundup.
    Windows之svn问题
    Embeded linux之地址映射
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4085147.html
Copyright © 2011-2022 走看看