当前位置: 首页 > 后端技术 > Python

LeetCode102.二叉树层序遍历

时间:2023-03-26 17:49:06 Python

解题思路是在while循环中遍历每一层(curr_node_list),将curr_node_list中各元素的val存入该层的值列表(temp_val_list)中,存入每一层的left和rightcurr_node_list中的元素依次放入该层的子层中。遍历list(temp_son_list)层节点后,退出条件更新curr_node_list:curr_node_list为空原标题链接欢迎在我的博客上轻松探索更多想法代码类解决方案:deflevelOrder(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=[]forfatherincurr_node_list:iffather:temp_val_list.append(father.val)尝试:temp_son_list.append(father.left)除了:通过try:temp_son_list.append(father.right)除了:通过if(temp_val_list):result.append(temp_val_list)curr_node_list=temp_son_列表返回结果