使用预序和顺序序列重建二叉树

时间:2016-03-21 01:32:38

标签: python recursion binary-tree

我编写了以下代码,但每次运行程序时都显示结果

File "D:\study\ML\binaryTree.py", line 31, in buildTree
    root.left = self.buildTree(preorder[1:rootvalue],inorder[0:rootvalue-1])
File "D:\study\ML\binaryTree.py", line 30, in buildTree
    root = TreeNode(rootvalue)
RuntimeError: maximum recursion depth exceeded`

必须递归解决,我真的不知道是什么问题。我写的代码:

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

class Solution:
    def buildTree(self, preorder, inorder):
        if preorder == None or inorder == None:
            return None
        if len(preorder) != len(inorder):
            return None

        length = len(preorder)
        rootvalue = 0
        for i in range(0,length):
            if inorder[i] == preorder[0]:
                rootvalue = i
                break
        if rootvalue == length-1 and inorder[rootvalue] != preorder[0]:
            return None
        root = TreeNode(rootvalue)
        root.left = self.buildTree(preorder[1:rootvalue],inorder[0:rootvalue-1])
        root.right = self.buildTree(preorder[rootvalue+1:length],inorder[rootvalue+1:length])
        print root.val,'->'
        return root
if __name__ == '__main__':
    sul = Solution()
    pre = [1,2,3]
    inorder = [2,1,3]
    sul.buildTree(pre,inorder)

1 个答案:

答案 0 :(得分:0)

您没有任何代码可以防止空列表,因此您的递归没有基本情况。可能代替您的preorder == None or inorder == None测试,您需要if not preorder or not inorder(因为如果列表为空,则列表为“falsey”)。