Python 代码实现二叉树生成
以下是 Python 语言的二叉树生成代码,具体实现方式可能有所不同:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, inorder):
'':type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
''
if not preorder or not inorder:
return None
root_val = preorder[0]
root = TreeNode(root_val)
index = inorder.index(root_val)
root.left = buildTree(preorder[1:index + 1], inorder[:index])
root.right = buildTree(preorder[index + 1:], inorder[index + 1:])
return root
该代码实现了通过先序遍历和中序遍历构建二叉树的算法。其中,通过先序遍历获取到根节点的值,然后在中序遍历中找到该值的位置,从而确定左子树和右子树的中序遍历序列。接着,通过递归的方式,不断构建左右子树,直到构建完整个二叉树。
原文地址: https://www.cveoy.top/t/topic/nG1M 著作权归作者所有。请勿转载和采集!