程序媛詹妮弗
终身学习

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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

 

 

题意:

二叉树水平遍历

 

Solution1:Use a queue

 

code

 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 class Solution {
11     public List<List<Integer>> levelOrder(TreeNode root) { 
12         List<List<Integer>> result = new ArrayList<>();
13         //corner
14         if(root ==null) return result;
15         
16         Queue<TreeNode> queue = new LinkedList<>();
17         queue.add(root);
18         while(!queue.isEmpty()){
19             List<Integer> list = new ArrayList<>();
20             int size = queue.size();
21             for(int i = 0; i< size; i++){
22                 TreeNode node = queue.poll();
23                 list.add(node.val);
24                 if(node.left!=null){
25                     queue.add(node.left);
26                 }
27                 if(node.right!=null){
28                     queue.add(node.right);
29                 }
30             } 
31             result.add(list) ;
32         }
33        return result;        
34     }
35 }

 

posted on 2019-05-07 03:38  程序媛詹妮弗  阅读(158)  评论(0编辑  收藏  举报