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

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


    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    
    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
     
     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 ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
    12         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
    15         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    16         if(root == null) return result;
    17         queue.add(root);
    18         TreeNode nl = new TreeNode(Integer.MIN_VALUE);
    19         queue.add(nl);
    20         ArrayList<Integer> cur = new ArrayList<Integer>();
    21         while(queue.size() != 1){
    22             TreeNode rn = queue.remove(0);
    23             if(rn.val == Integer.MIN_VALUE){
    24                 queue.add(nl);
    25                 result.add(cur);
    26                 cur = new ArrayList<Integer>();
    27             }
    28             else{
    29                 if(rn.left != null) queue.add(rn.left);
    30                 if(rn.right != null) queue.add(rn.right);
    31                 cur.add(rn.val);
    32             }
    33         }
    34         result.add(cur);
    35         return result;
    36     }
    37 }
  • 相关阅读:
    神代码
    初读《代码大全》
    单词频度统计
    AFO
    bzoj4816: [Sdoi2017]数字表格
    bzoj4006: [JLOI2015]管道连接
    bzoj4774: 修路
    bzoj3209: 花神的数论题
    bzoj4521: [Cqoi2016]手机号码
    COGS2314. [HZOI 2015] Persistable Editor
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426334.html
Copyright © 2020-2023  润新知