题目链接:
145.二叉树的后序遍历
1、后序遍历
主要想说这个题目和N叉树一样,用了一个迭代的方法去解决。二叉树的后续是左、右、根。利用栈的数据结构,进行根、右、左的遍历。然后把最终遍历的结果进行反转就可以了。
# 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: TreeNode) -> List[int]:
if not root:
return []
#递归
res = []
def helper(root):
if not root:
return
helper(root.left)
helper(root.right)
res.append(root.val)
helper(root)
return res
#迭代
stack,res = [root,],[]
while 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]
2、中序遍历(递归模板比较特殊)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
#递归法
res = []
def helper(root):
if not root:
return
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
#迭代法
stack,res = [],[]
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
3、先序遍历
先序的顺序是:根->左->右;采用迭代的话,肯定使用栈。那么先进右子树,再进左子树。这样保证左子树是先出的。就可以保证先序遍历的顺序。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
#递归
res = []
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
#迭代
stack,res = [root,],[]
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
总结:前序和后序的迭代模板是一样的,但是中序不可以,原因在于前序和后序遍历的根节点要不在最前面,要不再最后面;中序遍历的根节点刚好在中间,因此没办法使用那两个模板,只能使用双while循环递归,比较特殊。