51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)
生活随笔
收集整理的這篇文章主要介紹了
51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定兩個整數數組 inorder 和 postorder ,其中 inorder 是二叉樹的中序遍歷, postorder 是同一棵樹的后序遍歷,請你構造并返回這顆?二叉樹?。示例 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
總結
以上是生活随笔為你收集整理的51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 50. Leetcode 105. 从前
- 下一篇: 53. Leetcode 112. 路径