解題思路
在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