
1.递归的思想:通过前序序列找到根节点,然后在中序中分为左右子树.
2.index:找到值对应的索引位置返回
3.递归函数何时停止的条件很重要
# -*- 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
if not pre or not tin:
return None
root=TreeNode(pre[0])
val=tin.index(pre[0])
root.left=self.reConstructBinaryTree(pre[1:val+1],tin[:val])
root.right=self.reConstructBinaryTree(pre[val+1:],tin[val+1:])
return root
博客介绍了递归思想在处理树的前序和中序序列中的应用,通过前序序列确定根节点,在中序序列中划分左右子树。还提到了查找值对应索引位置的方法,强调递归函数停止条件的重要性。
172

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



