解题考点
1.对前序遍历与中序遍历的理解程度。
2.把构建二叉树的大问题分解成构建左、右子树的两个小问题。
解题笔记
-
前序遍历:根节点总是在第一位
-
中序遍历:根节点在序列中间
通过前序遍历确认根节点的值 (val) 在到中序遍历找到根节点的指针,进而分出左子树与右子树,并返回根节点 (root) -
停止递归条件:当前序遍历以及后序遍历皆没有值的时候,代表已无根节点,返回 None
Python 代码
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
if pre and tin:
# write code here
# 1.找到前序遍历结果的根节点值
root = TreeNode(pre.pop(0))
# 2.透过根节点的值在中序遍历结果找到指针
tin_root_ix = tin.index(root)
# 前序遍历的左子树, 右子树
# pre[:tin_root_ix], pre[tin_root_ix:]
# 中序遍历的左子树, 右子树
# tin[:tin_root_ix], tin[tin_root_ix+1:]
# 使用递归:左节点, 右节点
root.left = self.reConstructBinaryTree(pre, tin[:tin_root_ix])
root.right = self.reConstructBinaryTree(pre, tin[tin_root_ix+1: ])
return root
else:
return None