102. 二叉树的层次遍历
程序员文章站
2022-05-20 10:34:56
...
题目描述
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
知识点
二叉树、层次遍历
Qiang的思路
# 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 []
list=[root,'#']
result=[]
cur=[]
while list!=['#']:
c=list[0]
list.pop(0)
if c=='#':
list.append('#')
result.append(cur)
cur=[]
else:
list.append(c.left) if c.left!=None else None
list.append(c.right) if c.right!=None else None
cur.append(c.val)
result.append(cur)
return result
作者原创,如需转载及其他问题请邮箱联系:[email protected]。
个人网站:https://www.myqiang.top。
上一篇: 删除指定文件夹下所有文件
下一篇: ssh自动化登陆脚本加别名