题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
样例
输入
[1,2,4,7,3,5,6,8]
[4,7,2,1,5,3,8,6]
输出
# 树的层次遍历结果:
[1,2,3,4,5,6,7,8]
思路
《剑指offer》P55
主要步骤——
- preOrder中的第一个元素是当前子树的root;
- 如果当前只有一个元素,则构建节点并返回该节点;如果有多个元素则继续;
- 找到root 在inOrder中的下标;
- 根据root和inOrder序列,计算左右子树的长度;
- 递归构建root的左右子树。
code
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
root = None
if pre and tin and len(pre) == len(tin):
root = self.construct(pre, tin, 0, len(pre) - 1, 0, len(tin) - 1)
return root
def construct(self, pre, tin, pStart, pEnd, inStart, inEnd):
pRoot = TreeNode(pre[pStart])
# 找到中序遍历中,头结点的位置
index = inStart
while index <= inEnd and tin[index] != pRoot.val:
index += 1
# 计算左右子树的长度
leftLen = index - inStart
rightLen = inEnd - index
# 构建左右子树
if leftLen > 0:
pRoot.left = self.construct(pre, tin, pStart + 1, pStart + leftLen, inStart, index - 1)
if rightLen > 0:
pRoot.right = self.construct(pre, tin, pEnd - rightLen + 1, pEnd, index + 1, inEnd)
return pRoot
473




被折叠的 条评论
为什么被折叠?



