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

代码如下,开袋即食

复制代码
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

学生所做,记录学习。

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

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

相关推荐
TechNomad14 分钟前
二叉堆&大根堆&小根堆的介绍和使用
数据结构
发疯幼稚鬼36 分钟前
图的存储与拓扑排序
数据结构·算法·排序算法·拓扑学
LYFlied1 小时前
【每日算法】LeetCode 5. 最长回文子串(动态规划)
数据结构·算法·leetcode·职场和发展·动态规划
雪花desu2 小时前
【Hot100-Java中等】/LeetCode 128. 最长连续序列:如何打破排序思维,实现 O(N) 复杂度?
数据结构·算法·排序算法
程序员阿鹏3 小时前
如何保证写入Redis的数据不重复
java·开发语言·数据结构·数据库·redis·缓存
历程里程碑4 小时前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode
Helibo444 小时前
2025年12月gesp3级题解
数据结构·c++·算法
靠沿4 小时前
Java数据结构初阶——堆与PriorityQueue
java·开发语言·数据结构
禾叙_4 小时前
HashMap
java·数据结构·哈希算法
zcbdandan5 小时前
JNA内存对齐导致的结构体数组传输错误
数据结构·算法