思想:后序遍历是:左右根,我们可以反过来进行,根右左的遍历,这样直接使用栈就可以,然后对结果反转。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root):
res = []
stack = []
if root == None:
return res
stack.append(root)
while len(stack) > 0:
node = stack.pop()
res.append(node.val)
if node.left != None:
stack.append(node.left)
if node.right != None:
stack.append(node.right)
res.reverse()
return res
网友评论