429. N叉树的层序遍历
题意
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
解题思路
和二叉树的层次遍历的思想一样;
实现
class Solution(object):
def levelOrder(self, root):
"""
超出时间限制
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
stack, stack_tmp = [root], []
result = [[root.val]]
while stack:
cur = stack.pop()
for child in cur.children:
stack_tmp.insert(0, child)
if not stack and stack_tmp:
# 时间超出的原因可能在这,遍历一边接着又进行反转,花费时间可能比较多;
result.append([tmp.val for tmp in stack_tmp][::-1])
stack = stack_tmp[:]
stack_tmp = []
return result
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if not root:
return []
stack, stack_tmp = [root], []
result = [[]]
while stack:
cur = stack.pop()
result[-1].append(cur.val)
for child in cur.children:
stack_tmp.insert(0, child)
if not stack and stack_tmp:
stack = stack_tmp[:]
stack_tmp = []
result.append([])
return result
def levelOrder(self, root):
"""
递归实现,时间超出限制
:type root: TreeNode
:rtype: List[List[int]]
"""
result = []
if not root:
return result
def helper(node, depth, res):
"""
利用前序遍历的思想
"""
if not node:
return
# 超出递归的长度表明是新的一层,则新添加数组
if depth >= len(res):
res.append([])
# 可以理解成每个node都能对应到树的depth
res[depth].append(node.val)
for child in node.children:
helper(child, depth+1, res)
helper(root, 0, result)
return result