【LeetCode】105. 从前序与中序遍历序列构造二叉树 106. 从中序与后序遍历序列构造二叉树

105. 从前序与中序遍历序列构造二叉树

这道题也是经典的数据结构题了,有时候面试题也会遇到,已知前序与中序的遍历序列,由前序遍历我们可以知道第一个元素就是根节点,而中序遍历的特点就是根节点的左边全部为左子树,右边全部为右子树,再依次遍历前序序列,分割中序序列,不断结合这两个序列,就可以写代码了。详细说明都在代码中。因为前序是根左右,中序是左根右。

算法代码

java 复制代码
class Solution {
    private int preindex;  //成员变量 是遍历前序数组的索引 弄成成员变量比较好
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inleft,int inright){

        if(inleft>inright) return null;  //说明当前节点无左右子节点了
        TreeNode root = new TreeNode(preorder[preindex]);
        int index = find(inorder,preorder[preindex]); //找在中序数组中的索引,用来分组
        preindex++; 
        root.left = buildTreeChild(preorder,inorder,inleft,index-1); //先递归并返回当前节点的左子节点
        root.right = buildTreeChild(preorder,inorder,index+1,inright); //后递归并返回当前节点的右子节点
        return root;  //最后返回当前节点

    }

    public static int find(int[] inorder,int key){ //用来找每个根节点在后序数组中的下标,并返回下标
        int i = 0;
        while(inorder[i]!=key){
            i++;
        }
        return i;
    }
}

106. 从中序与后序遍历序列构造二叉树

此题与上个题几乎一模一样,区别在于,是已知中序和后序,而后序的特点是最后一个元素,为根节点,故要对后序序列进行从后往前遍历。并且递归返回左右子树的顺序也要发生改变。剩下的就和前一个代码一样了。因为中序是左根右,后序是左右根。

算法代码

java 复制代码
class Solution {

    private int postindex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postindex = postorder.length-1;  //指向序列最后一个元素,倒序遍历
        return buildTreeChild(postorder,inorder,0,postorder.length-1);

    }

     private TreeNode buildTreeChild(int[] postorder,int[] inorder ,int inleft,int inright){
        if(inleft>inright) return null;
        TreeNode root = new TreeNode(postorder[postindex]);
        int index = find(inorder,postorder[postindex]);
        postindex--;
        root.right = buildTreeChild(postorder,inorder,index+1,inright); //这里有区别
        root.left = buildTreeChild(postorder,inorder,inleft,index-1); //有区别
        return root;

    }
    private static int find(int[] inorder,int key){
        int i = 0;
        while(inorder[i] != key){
            i++;
        }
        return i;
    }
}
相关推荐
Seven97几秒前
数据结构-堆
java
D_FW几秒前
数据结构第一章:绪论
数据结构·考研
ysn111113 分钟前
简单多边形三角剖分---耳切法(含源码)
算法
e疗AI产品之路4 分钟前
一文介绍Philips DXL心电图算法
算法·pan-tompkins·心电分析
SimonKing7 分钟前
你的网站SSL证书又要过期了?这个工具能让你永久告别焦虑
java·后端·程序员
CryptoRzz8 分钟前
印度交易所 BSE 与 NSE 实时数据 API 接入指南
java·c语言·python·区块链·php·maven·symfony
YGGP11 分钟前
【Golang】LeetCode 21. 合并两个有序链表
leetcode·链表·golang
梵得儿SHI11 分钟前
SpringCloud 核心组件精讲:Sentinel 熔断限流全攻略-流量控制、熔断降级、热点参数限流(含 Dashboard 部署 + 项目集成实操)
java·spring cloud·sentinel·熔断降级·热点参数限流·微服务流量控制
麦兜*11 分钟前
Spring Boot 3.x 升级踩坑大全:Jakarta EE 9+、GraalVM Native 与配置迁移实战
java·spring boot·后端·spring·spring cloud
小袁顶风作案14 分钟前
leetcode力扣——135.分发糖果
算法·leetcode·职场和发展