题目描述:
- 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树,假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如,输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则重建如下图所示的二叉树并输出它的头结点。二叉树节点的定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
解题思路:
- 根据二叉树的前序遍历可和中序遍历可以确定根节点的值、左子树节点的值和右子树节点的值。
- 首先在前序中确定根节点,然后再中序中找到对应的根节点位置,左边为左子树、右边为右子树,完成划分
- 以上述同样的方法递归构建左子树、右子树即可。
class BinaryTreeNode:
def __init__(self, val):
self.val = val
self.LeftNode = None
self.RightNode = None
class Solution:
def __init__(self, list_pre, list_in):
self.list_pre = list_pre
self.list_in = list_in
def ReconstructTree(self):
if self.list_pre is None or self.list_in is None:
return None
return self.ConstructCore(0, len(self.list_pre) - 1, 0, len(self.list_in) - 1)
def ConstructCore(self, startPreoder, endPreorder, startInorder, endInorder):
rootValue = self.list_pre[startPreoder]
root = BinaryTreeNode(rootValue)
root.LeftNode = root.RightNode = None
if startPreoder == endPreorder:
if startPreoder == endPreorder and self.list_pre[startPreoder] == self.list_in[startInorder]:
return root
else: raise ValueError('invalid input')
rootInorder = startInorder
while rootInorder <= endInorder and self.list_in[rootInorder] != rootValue:
rootInorder += 1
if rootInorder == endInorder and self.list_in[rootInorder] != rootValue:
raise ValueError('invalid input')
leftLength = rootInorder - startInorder
leftPreorderEnd = startPreoder + leftLength
if leftLength > 0:
root.LeftNode = self.ConstructCore(startPreoder + 1, leftPreorderEnd, startInorder, rootInorder - 1)
if leftLength < endPreorder - startPreoder:
root.RightNode = self.ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder)
return root