题意描述:
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
示例:
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解题思路:
层序遍历: 队列 + 宽度优先搜索。
代码:
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[List[int]]:
if root == None:
return []
ret = []
tmp = [root]
while True:
nextLineNode = []
nextLineValue = []
while len(tmp) != 0: # 对每一层,从左到右,记录值,记录left & right
node = tmp.pop(0)
nextLineValue.append(node.val)
if node.left:
nextLineNode.append(node.left)
if node.right:
nextLineNode.append(node.right)
ret.append(nextLineValue)
if len(nextLineNode) == 0: # 直到下一行已经没有元素,退出外层循环
break
else:
tmp = nextLineNode
return ret
Java :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null){
return new ArrayList<List<Integer>>();
}
List<List<Integer>> ret = new ArrayList<List<Integer>>();
Queue<TreeNode> nextLineNode = new LinkedList<TreeNode>();
nextLineNode.offer(root);
while(nextLineNode.isEmpty() == false){
Queue<TreeNode> helper = new LinkedList<TreeNode>();
List<Integer> nextLineValue = new ArrayList<Integer>();
while(nextLineNode.isEmpty() == false){
TreeNode node = nextLineNode.poll();
if(node != null){
nextLineValue.add(node.val);
if(node.left != null){
helper.offer(node.left);
}
if(node.right != null){
helper.offer(node.right);
}
}
}
nextLineNode = helper;
ret.add(nextLineValue);
}
return ret;
}
}
易错点:
- 一些测试点
[3,9,20,null,null,15,7]
[3,9,null,20,null]
[1,null,null]
[]
- 答案
[[3],[9,20],[15,7]]
[[3],[9],[20]]
[[1]]
[]
List<List<Integer>> = new ArrayList<ArrayList<Integer>>()
是非法的。
总结:
- 基础不牢,地动山摇。