思路:二叉树的前序遍历,存到res中返回。
Python:
#dfs
class Solution: def levelOrder(self, root: TreeNode) -> List[int]: res=[] def dfs(root): if not root: return None res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return res
#bfs
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
res,queue=[],[]
if not root:
return res
queue.append(root)
while queue:
node=queue.pop(0)
res.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return res