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

代码如下,开袋即食

复制代码
class Solution {
    private Map<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i =0;i<preorder.length;i++){
            map.put(inorder[i],i);
        }
        return build(preorder,inorder,0,preorder.length-1,0,preorder.length-1);
    }
    public TreeNode build(int[] preorder,int[] inorder,int p_left,int p_right,int i_left,int i_right){
        if(p_left>p_right||i_left>i_right) return null;
        int p_root = p_left;//前序比那里的第一个节点就是根节点
        int i_root = map.get(preorder[p_root]);//在中序遍历中定位根节点的位置
        TreeNode root = new TreeNode(preorder[p_left]);
        int left_size_tree = i_root-p_left;//获得左子树的长度
        root.left = build(preorder,inorder,p_left+1,p_left+left_size_tree,i_left,i_root-1);
        root.right = build(preorder,inorder,p_left+left_size_tree+1,p_right,i_root+1,i_right);
        return root;

    }
}

同样这里需要注意前序遍历和中序遍历的左右指针的一个边界问题。

左指针遍历的时候

前序左边界:p_left+1即可

前序右边界:p_left+left_size_tree

中序左边界:i_left

中序右边界:i_root-1

右指针遍历的时候

前序左边界:p_left+left_size_tree+1即可

前序右边界:p_right

中序左边界:i_root+1

中序右边界:i_right

学生所做,记录学习。

另外有一题类似,解法和本题有异曲同工之处。

从中序和后序遍历序列构造二叉树

相关推荐
野渡拾光2 小时前
【考研408数据结构-05】 串与KMP算法:模式匹配的艺术
数据结构·考研·算法
pusue_the_sun9 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
liang_jy15 小时前
数组(Array)
数据结构·面试·trae
要做朋鱼燕16 小时前
【数据结构】用堆解决TOPK问题
数据结构·算法
秋难降17 小时前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
Jayyih19 小时前
嵌入式系统学习Day19(数据结构)
数据结构·学习
DdduZe19 小时前
8.19作业
数据结构·算法
PyHaVolask19 小时前
链表基本运算详解:查找、插入、删除及特殊链表
数据结构·算法·链表
1白天的黑夜121 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
花开富贵ii21 小时前
代码随想录算法训练营四十六天|图论part04
java·数据结构·算法·图论