当前位置:   article > 正文

从中序与后序遍历序列构造二叉树Python解法_python给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉

python给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
 

例:

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

解析:

后序遍历的最后一个值即为根节点,在中序遍历中找到该值,在中序遍历中,该值得左边为左子树,右边为右子树,每次遍历可以确定一个值,即根节点。

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution(object):
  8. def buildTree(self, inorder, postorder):
  9. """
  10. :type inorder: List[int]
  11. :type postorder: List[int]
  12. :rtype: TreeNode
  13. """
  14. def build(pos_left, pos_right, mid_left, mid_right):
  15. if pos_left > pos_right or mid_left > mid_right: # 停止条件
  16. return None
  17. root = TreeNode(postorder[pos_right]) # 构建节点
  18. mid_root = mid_left
  19. while mid_root <= mid_right and inorder[mid_root] != postorder[pos_right]: #找寻根节点
  20. mid_root += 1
  21. diff = mid_root - mid_left # 左子树的长度
  22. root.left = build(pos_left, pos_left + diff -1, mid_left, mid_root - 1) # 构建左子树
  23. root.right = build(pos_left + diff, pos_right - 1, mid_root + 1, mid_right) # 构建右子树
  24. return root # 返回构建好的树
  25. return build(0, len(postorder) - 1, 0, len(inorder) - 1)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/380521
推荐阅读
相关标签
  

闽ICP备14008679号