力扣 105. 从前序与中序遍历序列构造二叉树

前置

1
2
3
4
5
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

解法

1
2
3
4
5
6
7
def buildTree(preorder, inorder):
if not preorder: return
root = TreeNode(preorder[0])
root_idx = inorder.index(preorder.pop(0))
root.left = self.buildTree(preorder[:root_idx], inorder[:root_idx])
root.right = self.buildTree(preorder[root_idx:], inorder[root_idx + 1:])
return root
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors:2820 | Views:3143
  • 小站在各种崩坏中坚持了: 1895天23小时51分54秒

请我喝杯咖啡吧~

支付宝
微信