zoukankan      html  css  js  c++  java
  • 由二叉树的前序、中序遍历结果,重建二叉树

    前序遍历的第一个元素为根节点,在中序遍历中:根节点左右两侧即为左右子树的中序遍历结果。

    思路:

    1. 找到前序遍历的根节点在中序遍历中的位置
    2. 使用两个数组分别存储左子树的前序、中序遍历结果,递归构建左子树(中序结果为空--> 父节点为叶节点)
    3. 使用两个数组分别存储右子树的前序、中序遍历结果,递归构建右子树
    4. 将左右子树连接在当前根节点上
    • JavaScript实现
    function TreeNode(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
    function reConstructBinaryTree(pre, vin)
    {
        const len = vin.length;
        if(!len) return null;//父节点为叶节点
        let root = new TreeNode(pre[0]);//当前根节点
        let target_idx = 0;
        for(let i = 0; i < len; i++){
            if(vin[i] == pre[0]){
                target_idx = i;
                break;
            }
        }
        let cur_pre = [],
            cur_vin = [];//左右子树的前中序遍历存储数组
        for(let i = 1; i <= target_idx; i++){//左子树
            cur_pre.push(pre[i]);//根节点之后加入与中序遍历等长的序列
            cur_vin.push(vin[i - 1]);//根节点之前的全部加入
        }
        root.left = reConstructBinaryTree(cur_pre, cur_vin);
        cur_pre.splice(0, cur_pre.length);
        cur_vin.splice(0, cur_vin.length);
        for(let i = target_idx + 1; i < len; i++){
            cur_pre.push(pre[i]);
            cur_vin.push(vin[i]);
        }
        root.right = reConstructBinaryTree(cur_pre, cur_vin);
        return root;
    }
    
  • 相关阅读:
    3.1《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——下载文件
    rem实现手机页面自动缩放
    Git 常用命令
    使用 canvas+JS绘制钟表
    JS 操作数组的方法
    Node.js Request方法
    兼容浏览器的点击事件
    ES6知识点
    上传项目到github上
    JavaScript 编码风格
  • 原文地址:https://www.cnblogs.com/honey-cat/p/14634511.html
Copyright © 2011-2022 走看看