题目:
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] ]按层访问二叉树,并返回访问结果。
解题思路:
递归+广度优先(BFS)
每个递归中,先得到当前层的所有结点(now);通过当前层的结点得到数值,保存到结果中(res);然后根据当前层得到下一层的结点(next_term);
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root): #root是树的根节点
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
res = []
self.excute([root],res)
return res
def excute(self,now,res): #递归体,now是当前层的节点,next_term是下一层节点,res是保存得到的结果。
if not now:
return
tmp = [] #tmp 保存了当前层的数值
next_term = []
for one in now:
tmp.append(one.val)
if one.left:
next_term.append(one.left)
if one.right:
next_term.append(one.right)
res.append(tmp)
self.excute(next_term,res)