探究根据先序遍历与中序遍历求整棵树的非递归写法

来源:互联网 发布:乡镇网络舆情预警机制 编辑:程序博客网 时间:2024/04/30 06:27

emmmmm

先把递归思路讲一下

class Solution:    def reConstructBinaryTree(self, pre, nex):        if pre == []:            return        head = TreeNode(pre[0])        if pre.__len__() == 1:            return head        head_index = nex.index(pre[0])        head.left = self.reConstructBinaryTree(pre[1:head_index+1],nex[0:head_index])        head.right = self.reConstructBinaryTree(pre[head_index+1::], nex[head_index+1::])        return head

递归的终结点是当提供的先序遍历与中序遍历长度为1时,即确认这个节点是上个节点的子节点,或者这个节点为None

下面探究一下非递归的思路,就是用循环去解决

嗯,先挖坑,过会在写

阅读全文
0 0
原创粉丝点击