# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return int整型一维数组
#
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]: #迭代法1
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
# 中结点先处理
result.append(node.val)
# 左孩子先入栈
if node.left:
stack.append(node.left)
# 右孩子后入栈
if node.right:
stack.append(node.right)
# 将最终的数组翻转
return result[::-1]
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]: #迭代法2
result = []
st = []
if root:
st.append(root)
while st:
node = st.pop()
if node != None:
st.append(node) #中
st.append(None)
if node.right: #右
st.append(node.right)
if node.left: #左
st.append(node.left)
else:
node = st.pop()
result.append(node.val)
return result
class Solution:
def postorderTraversal(self , root: TreeNode) -> List[int]: #递归法
# write code here
if root is None: return None
result = []
def traversal(root: TreeNode):
if root is None:
return None
if root.left: traversal(root.left)
if root.right: traversal(root.right)
result.append(root.val)
traversal(root)
return result