Skip to content

面试题 6 重建二叉树 的一处写法可以改进 #1

@mookrs

Description

@mookrs

root.right = construct_tree(preorder[-len(right):], right)

这里如果 right[] 的话,会导致 preorder[-len(right):] 的值变成该 preorder 的副本,前序遍历和中序遍历长度不一致,显然是不合理的。

应该写成

root.right = construct_tree(preorder[index + 1:], right)

或者对这一段重新整理一下

index = inorder.index(preorder[0])
root = TreeNode(preorder[0])
root.left = construct_tree(preorder[1:index + 1], inorder[0:index])
root.right = construct_tree(preorder[index + 1:], inorder[index + 1:])
return root

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions