给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历: [5,6,3,2,4,1].
- 思路
- 递归
class Solution:
def postorder(self, root: 'Node') -> List[int]:
res=[]
def helper(root):
if(root is None):
return
for child in root.children:
helper(child)
res.append(root.val)
helper(root)
return res
- 迭代
class Solution:
def postorder(self, root: 'Node') -> List[int]:
res=[]
stack=[root]
while(stack):
tmp=stack.pop()
if(not tmp):
continue
res.append(tmp.val)
for child in tmp.children:
stack.append(child)
return res[::-1]
- 颜色标记法
class Solution:
def postorder(self,root):
res=[]
stack=[('white',root)]
while(stack):
color,tmp=stack.pop()
if(not tmp):
continue
if(color=='gray'):
res.append(tmp.val)
else:
stack.append(('gray',tmp))
for child in tmp.children[::-1]:
stack.append(('white',child))
return res