解题思路
在while循环中遍历每一层(curr_node_list)
将curr_node_list中每一个元素的val存入该层的值的list(temp_val_list)
将curr_node_list中每一个元素的left和right依次存入该层的子结点的list(temp_son_list)
层遍历结束后,更新curr_node_list
while退出条件:curr_node_list为空
代码
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
result=[]
curr_node_list=[]
curr_node_list.append(root)
while(curr_node_list):
temp_son_list=[]
temp_val_list=[]
for father in curr_node_list:
if father:
temp_val_list.append(father.val)
try:
temp_son_list.append(father.left)
except:
pass
try:
temp_son_list.append(father.right)
except:
pass
if(temp_val_list):
result.append(temp_val_list)
curr_node_list=temp_son_list
return result
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。