二叉树前、中、后序遍历及还原二叉树

二叉树:
二叉树

  • 前序遍历
    根节点 —>左子树—>右子树
    顺序:根节点 —>前序遍历左子树(根->左->右)—>前序遍历右子树(根->左->右)

遍历结果:A-B-C-D-E-F-G-H-I

  • 中序遍历
    左子树—>根节点—>右子树
    顺序:中序遍历左子树(左->根->右)—>根节点—>中序遍历右子树(左->根->右)

遍历结果:D-C-B-E-F-A-H-G-I

  • 后序遍历
    左子树—>右子树—>根节点
    顺序:后序遍历左子树(左->右->根)—>后序遍历右子树(左->右->根)—>根节点

遍历结果:D-C-F-E-B-H-I-G-A


总结
先序、中序、后序中的这个”顺序“是对于根节点而言的,例如中序就是中间访问根节点,后序就是最后访问根节点。

只有前序和后序遍历无法还原二叉树:前序和后序都能确定根节点,但是无法确认左子树和右子树。
前序+中序 or 后序+中序 可以还原二叉树:中序遍历是用来区分左右子树的。根据前序或后序得到的根节点,在中序遍历中,根节点左侧的是左子树,右侧的是右子树。由此,即可还原二叉树。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
递归构建二叉树: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def build_tree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root = TreeNode(root_val) index = inorder.index(root_val) root.left = build_tree(preorder[1:index+1], inorder[:index]) root.right = build_tree(preorder[index+1:], inorder[index+1:]) return root ``` 其,preorder 表示序遍历序列,inorder 表示中序遍历序列。 序遍历:根节点 -> 左子树 -> 右子树 中序遍历:左子树 -> 根节点 -> 右子树 后序遍历:左子树 -> 右子树 -> 根节点 序遍历的第一个元素即为当树的根节点,然后找到它在中序遍历的位置,这样就可以确定左子树和右子树的大小,并进行递归构建二叉树序遍历: ```python def pre_order(root): if not root: return print(root.val, end=' ') pre_order(root.left) pre_order(root.right) ``` 中序遍历: ```python def in_order(root): if not root: return in_order(root.left) print(root.val, end=' ') in_order(root.right) ``` 后序遍历: ```python def post_order(root): if not root: return post_order(root.left) post_order(root.right) print(root.val, end=' ') ``` 示例: ```python preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = build_tree(preorder, inorder) pre_order(root) # 1 2 4 5 3 6 7 print() in_order(root) # 4 2 5 1 6 3 7 print() post_order(root) # 4 5 2 6 7 3 1 ``` 输出结果为: ``` 1 2 4 5 3 6 7 4 2 5 1 6 3 7 4 5 2 6 7 3 1 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳叶lhy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值