重建二叉树
- 已知的前序或者后序遍历中找到根节点;
- 在中序遍历中根据根节点的值找到其位置,找出二叉树的左右子树;
- 分治法:把每个左右子树看作一个二叉树,重复以上步骤,可以使用递归思想。
class TreeNode:
"""二叉树节点"""
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def reConstructBinaryTree(self, mid, post):
if not mid or not post:
"""递归出口"""
return
root = TreeNode(post[-1])
index = mid.index(root.val)
root.left = self.reConstructBinaryTree(mid[:index], post[:index])
root.right = self.reConstructBinaryTree(mid[index + 1:], post[index:-1])
return root
def pre_travel(self, root):
"""前序遍历"""
if root != None:
print(root.val, end='')
self.pre_travel(root.left)
self.pre_travel(root.right)
class Solution:
def reConstructBinaryTree(self, pre, mid):
if not pre or not mid:
return
root = TreeNode(pre[0])
index = mid.index(root.val)
root.left = self.reConstructBinaryTree(pre[1:index+1], mid[:index])
root.right = self.reConstructBinaryTree(pre[index+1:], mid[index + 1:])
return root
if __name__ == '__main__':
pre = 'ABDEHCGF'
mid = 'DBHEAGCF'
post = 'DHEBGFCA'
******** 中序后序得前序 ********
s = Solution()
root = s.reConstructBinaryTree(mid, post)
s.pre_travel(root)
******** 前序中序得后序 ********
s = Solution()
s.reConstructBinaryTree(pre, mid)