題目:
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
代碼:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
s = []
list=[]
s.append(root)
cur = root
pre = None
p=root
if root:
while len(s)!= 0:
cur=s[-1]
if ( cur.left==None and cur.right==None ) or ( pre!=None and ( pre==cur.right or pre==cur.left ) ):
list.append(cur.val)
pre=cur
s.pop()
else:
if cur.right!=None:
s.append(cur.right)
if cur.left!=None:
s.append(cur.left)
return list