每日一题(力扣)---从中序与后序遍历序列构造二叉树

本文介绍了如何利用后序遍历的特性确定根节点,通过递归方法将中序遍历和后序遍历转化为二叉树结构,提供了JavaScript代码实现buildTree函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

根据中序遍历和后序遍历的特性可知,后序遍历的最后一个元素为根元素。然后找到中序遍历中对应的序号。将中序遍历的划分为两部分,左边为左子树,右边为右子树。

方法

由思路可知,可以使用递归。递归函数的入口为划分的区间。left表示左端点,right表示右端点。

  1. 如果left和right相等说明当前节点没有左右孩子直接返回一个新的树节点。
  2. 设置一个count表示当前访问后序遍历中的元素。
  3. 设置一个索引值,表示后序遍历中元素在中序中的位置。
  4. 然后取postorder[count],遍历中序列表找到这个索引。
  5. 根据索引生成根节点。
  6. 递归左右子树。
  7. 遍历完成,返回节点。

代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, postorder) {
    let count = postorder.length
    const iter = function (left, right) {
        if (count <= 0) return
        count--
        if (left === right) {
            return new TreeNode(inorder[left])
        }
        let index
        for (let i = left; i <= right; i++) {
            if (inorder[i] === postorder[count]) {
                index = i
                break
            }
        }
        const node = new TreeNode(postorder[count])
        if(right >= index + 1)
        node.right = iter(index + 1, right)
        if(index - 1 >= left)
        node.left = iter(left, index - 1)
        return node
    }
    return iter(0, inorder.length - 1)
};

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值