Binary Tree Level Order Traversal(二叉树广度优先遍历或逐层遍历)
来源:https://leetcode.com/problems/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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
使用队列来存储每层的节点,然后每一层出队列后将其下一层入队列
Java
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 import java.util.LinkedList; 11 import java.util.Queue; 12 class Solution { 13 public List<List<Integer>> levelOrder(TreeNode root) { 14 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 15 List<List<Integer>> result = new ArrayList<List<Integer>>(); 16 TreeNode node = null; 17 queue.offer(root); 18 int queueSize = 0; 19 while(!queue.isEmpty()) { 20 List<Integer> levelResult = new ArrayList<Integer>(); 21 queueSize = queue.size(); 22 while(queueSize-- > 0) { 23 node = queue.poll(); 24 if(node == null) { 25 continue; 26 } 27 levelResult.add(node.val); 28 queue.add(node.left); 29 queue.add(node.right); 30 } 31 if(!levelResult.isEmpty()) { 32 result.add(levelResult); 33 } 34 } 35 return result; 36 } 37 }
Python
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def levelOrder(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: List[List[int]] 13 """ 14 if root == None: 15 return [] 16 level = [root] 17 results = [] 18 while level: 19 results.append([node.val for node in level]) 20 level = [kid for node in level for kid in (node.left, node.right) if kid] 21 return results