题目描述:
- 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
- 假设输入的前序遍历和中序遍历的结果中都不含有重复的数字。
- 例如:输入的前序遍历为{1,2,4,7,3,5,6,8}和中序遍历{4,7,2,1,5,3,8,6},则重建二叉树并输出它的头节点。
题目分析:
一些简要的思路:
在二叉树中:
- 前序遍历的根节点是第一个数字。输出顺序:根节点、左子树、右子树
- 中序遍历的根节点在中间位置。输出顺序:左子树、根节点、右子树
- 后序遍历的根节点是最后一个数字。输出顺序:根节点、左子树、右子树
详细思路:
- 前序遍历的第一个数字 1 就是根节点的值。
- 中序遍历中,根节点的位置在序列的中间,左子树的结点在根节点的左边,右子树的结点的值在根节点的右边。故数字 1 前面的三个数字都是左子树节点的值,数字 1 后面的数字都是右子树节点的值。
- 同样在前序遍历中,根节点后面的3个数字就是3个左子树节点的值,再后面的所有数字就是右子树的结点值。
- 这时,我们在前序和后序遍历中都找到了左右子树的对应的子序列。
- 再用递归的方法继续下去就好了!!
代码实现:
class TreeNode: # 先声明一个二叉树
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
# pre是前序遍历,tin是中序遍历
def reConstructBinaryTree(self,pre,tin):
if not pre and not tin: # 排空
return None
root = TreeNode(pre[0]) # 根节点
if set(pre) != set(tin):
return None
i = tin.index(pre[0]) # 根节点在中序遍历中的index
# 一直递归下去
root.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i]) # 左子树一直递归下去
root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:]) # 右子树一直递归下去
return root
def Print_res(root,lists): # 打印出后序遍历的数组列表
if root == None:
return lists
Print_res(root .left,lists)
Print_res(root .right,lists)
lists.append(root .val)
return lists
验证
#// 普通二叉树
#// 1
#// / \
#// 2 3
#// / / \
#// 4 5 6
#// \ /
#// 7 8
---------------------------------------------------
输入:
solution = Solution()
lists=[]
pre = [1,2,4,7,3,5,6,8]
tin = [4,7,2,1,5,3,8,6]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: [7, 4, 2, 5, 8, 6, 3, 1]
#// 所有结点都没有右子结点
#// 1
#// /
#// 2
#// /
#// 3
#// /
#// 4
#// /
#// 5
---------------------------------------------------
输入:
lists=[]
pre = [1, 2, 3, 4, 5]
tin = [5, 4, 3, 2, 1]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: [5, 4, 3, 2, 1]
#// 所有结点都没有左子结点
#// 1
#// \
#// 2
#// \
#// 3
#// \
#// 4
#// \
#// 5
---------------------------------------------------
输入:
lists=[]
pre = [1, 2, 3, 4, 5]
tin = [1, 2, 3, 4, 5]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: [5, 4, 3, 2, 1]
#// 树中只有一个结点
---------------------------------------------------
输入:
lists=[]
pre = [1]
tin = [1]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: [1]
#// 完全二叉树
#// 1
#// / \
#// 2 3
#// / \ / \
#// 4 5 6 7
---------------------------------------------------
输入:
lists=[]
pre = [1, 2, 4, 5, 3, 6, 7]
tin = [4, 2, 5, 1, 6, 3, 7]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: [4, 5, 2, 6, 7, 3, 1]
#// 输入空指针
---------------------------------------------------
输入:
lists=[]
pre = None
tin = None
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: []
#// 输入的两个序列不匹配
---------------------------------------------------
输入:
lists=[]
pre = [1, 2, 4, 5, 3, 6, 7]
tin = [4, 2, 8, 1, 6, 3, 7]
root = solution.reConstructBinaryTree(pre, tin)
print(Print_res(root,lists))
输出: []