[145. Binary Tree Postorder Traversal(https://leetcode.com/problems/binary-tree-postorder-traversal/)
题目描述
二叉树的后序遍历
思想 (递归)
(迭代) 先找到后序遍历的逆序根右左,然后再求得后序遍历。
解法1 左右根,递归。
# 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]
"""
if not root:
return None
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
解法2-1 迭代 - 类似前序遍历,再逆序。
# 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]
"""
res = []
stack = []
while root or stack:
while root:
stack.append(root)
res.append(root.val)
root = root.right
node = stack.pop()
root = node.left
return res[::-1]
解法2-2 迭代 - 类似前序遍历,再逆序。
# 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]
"""
res = []
stack = [root]
while root and stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
.