Python實現"N叉樹的前序遍歷"的兩種方法
阿新 • • 發佈:2019-02-16
給定一顆n叉樹,返回對它節點值的前序遍歷
例如,給定一個3叉樹:
返回它的前序遍歷為:[1,3,5,6,2,4]
注意:遞迴很簡單,請嘗試用迭代的方法完成
1、迭代
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
gBack = []
nodeList = [root]
while nodeList:
node = nodeList.pop(0)
if node:
gBack.append(node.val)
for i in node.children[::-1]:
nodeList.insert(0, i)
return gBack
2、遞迴
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
gBack = [root.val]
for node in root.children:
gBack += self.preorder(node)
return gBack
演算法題來自:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/description/