51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)
生活随笔
收集整理的這篇文章主要介紹了
51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定兩個(gè)整數(shù)數(shù)組 inorder 和 postorder ,其中 inorder 是二叉樹(shù)的中序遍歷, postorder 是同一棵樹(shù)的后序遍歷,請(qǐng)你構(gòu)造并返回這顆?二叉樹(shù)?。示例 1:輸入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
輸出:[3,9,20,null,null,15,7]
示例 2:輸入:inorder = [-1], postorder = [-1]
輸出:[-1]# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:if not postorder:return Noneroot = TreeNode(postorder[-1])rootIndex = inorder.index(root.val)root.left = self.buildTree(inorder[0:rootIndex], postorder[0:rootIndex])root.right = self.buildTree(inorder[rootIndex+1:],postorder[rootIndex:-1])return root
總結(jié)
以上是生活随笔為你收集整理的51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 50. Leetcode 105. 从前
- 下一篇: 53. Leetcode 112. 路径