給定一個 N 叉樹,返回其節點值的層序遍歷。 (即從左到右,逐層遍歷)。node
和二叉樹的層次遍歷的思想同樣;web
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