LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-03-07 23:39:50
...
题目
思路
递归构建左子树和右子树
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if not postorder: return None
if len(postorder) == 1:
return TreeNode(postorder[0])
index = -1
for i, v in enumerate(inorder):
if v == postorder[-1]:
index = i
break
node = TreeNode(postorder[-1])
if index > 0:
node.left = self.buildTree(inorder[:index], postorder[:index])
if index < len(inorder) - 1:
node.right = self.buildTree(inorder[index + 1:], postorder[index:len(postorder) - 1])
return node
推荐阅读
-
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal
-
leetcode 随笔 Construct Binary Tree from Preorder and Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
leetcode: binary-tree-postorder-traversal:后序遍历二叉树
-
LeetCode 94. Binary Tree Inorder Traversal
-
LeetCode145. Binary Tree Postorder Traversal(后序遍历)