【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;
    }
}
相关推荐
程序 代码狂人10 分钟前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
HDU-Dade1 小时前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法
人工智能·算法
2501_944521591 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
Xin7702 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
南归北隐2 小时前
Spring AI Alibaba Graph框架实现MCP数据库查询实战
java·后端·spring ai·mcp·spring ai mcp
古法老登瞎折腾2 小时前
大数据智能运维实战(九):让 AI 查日志——找到异常,也保留上下文
java·大数据·运维·人工智能·spring ai·mcp
ai大模型-探索者3 小时前
Function Call与MCP(区别、联系与实战)
java·服务器·网络
略略略咯咯3 小时前
啊啊啊啊啊
java·服务器·数据库
小郎君6583 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
SL_staff3 小时前
运维救火实战:钉钉API变更致薪资计算中断,如何用可视化逻辑引擎5分钟热修复
java·开源·全栈