目录
二叉树的遍历
遍历类型
(1)访问根结点
(2)遍历该结点的左子树(B)
(3)遍历该结点的右子树(C)
前序遍历:ABC(根结点在前)
中序遍历:BAC(根结点在中)
后序遍历:BCA(根结点在后)
对上面二叉树中的节点进行遍历。
前序遍历 12467835
中序遍历 47682135
后序遍历 78642531
区别在于:
前序:观察到一个结点后,即刻输出该节点的值,并继续遍历其左右子树。(根左右)
中序:观察到一个结点后,将其暂存,遍历完左子树后,再输出该节点的值,然后遍历右子树。(左根右)
后序:观察到一个结点后,将其暂存,遍历完左右子树后,再输出该节点的值。
题目:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解
递归算法
中序
# 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]:
def inorder(root):
if not root:
return
inorder(root.left)
ans.append(root.val)
inorder(root.right)
ans = []
inorder(root)
return ans
前序:
# 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]:
def inorder(root):
if not root:
return
ans.append(root.val)
inorder(root.left)
inorder(root.right)
ans = []
inorder(root)
return ans
后序:
# 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]:
def inorder(root):
if not root:
return
inorder(root.left)
inorder(root.right)
ans.append(root.val)
ans = []
inorder(root)
return ans
迭代算法
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
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
# # 前序,相同模板
# while stack or cur:
# while cur:
# res.append(cur.val)
# stack.append(cur)
# cur = cur.left
# cur = stack.pop()
# cur = cur.right
# return res
# # 后序,相同模板
# while stack or cur:
# while cur:
# res.append(cur.val)
# stack.append(cur)
# cur = cur.right
# cur = stack.pop()
# cur = cur.left
# return res[::-1]
总结最全系列: