题意描述:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
示例:
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
解题思路:
队列 + BFS
代码:
Python 方法一: 队列 + 循环
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
tmp = [root]
ret = []
while len(tmp) != 0:
node = tmp.pop(0)
if node != None:
ret.append(node.val)
tmp.append(node.left)
tmp.append(node.right)
return ret
Java 方法一:LinkedList 实现队列
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Queue;
import java.util.LinkedList;
class Solution {
public int[] levelOrder(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
Queue<TreeNode> tmp = new LinkedList<TreeNode>();
tmp.offer(root);
while(tmp.size() != 0){
TreeNode node = tmp.poll();
if(node != null){
ret.add(node.val);
tmp.offer(node.left);
tmp.offer(node.right);
}
}
int[] ans = new int[ret.size()];
for(int i=0; i<ret.size(); ++i){
ans[i] = ret.get(i);
}
return ans;
}
}
易错点:
- 一些测试用例:
[3,9,20,null,null,15,7]
[3,9,20,15,7,null,null]
[]
[1,null,null]
- 答案:
[3,9,20,15,7]
[3,9,20,15,7]
[]
[1]
总结: