python-leetcode-从中序与后序遍历序列构造二叉树

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

python 复制代码
# 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]) -> Optional[TreeNode]:
        if not inorder or not postorder:  # 如果任一遍历为空,返回 None
            return None
        
        # 根节点是后序遍历的最后一个元素
        root_val = postorder.pop()
        root = TreeNode(root_val)
        
        # 找到根节点在中序遍历中的位置
        root_index = inorder.index(root_val)
        
        # 划分右子树和左子树(注意:先处理右子树,因为后序遍历是左-右-根)
        right_inorder = inorder[root_index + 1:]
        left_inorder = inorder[:root_index]
        
        # 递归构建右子树和左子树
        root.right = self.buildTree(right_inorder, postorder)
        root.left = self.buildTree(left_inorder, postorder)
        
        return root
相关推荐
毅炼29 分钟前
hot100打卡——day14
java·数据结构·算法·leetcode·ai·深度优先·哈希算法
liliangcsdn33 分钟前
RL中GAE的计算过程详解
大数据·人工智能·算法
Hgfdsaqwr34 分钟前
内存泄漏检测与防范
开发语言·c++·算法
C雨后彩虹39 分钟前
优雅子数组
java·数据结构·算法·华为·面试
漫随流水1 小时前
leetcode回溯算法(46.全排列)
数据结构·算法·leetcode·回溯算法
We་ct1 小时前
LeetCode 68. 文本左右对齐:贪心算法的两种实现与深度解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻1 小时前
day67(1.26)——leetcode面试经典150
算法·leetcode·面试
iAkuya1 小时前
(leetcode) 力扣100 52腐烂的橘子(BFS)
算法·leetcode·宽度优先
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #148:排序链表(插入、归并、快速等五种实现方案解析)
算法·leetcode·链表·插入排序·归并排序·快速排序·链表排序
木井巳1 小时前
【递归算法】计算布尔二叉树的值
java·算法·leetcode·深度优先