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

代码如下,开袋即食

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

学生所做,记录学习。

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

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

相关推荐
不知名XL5 小时前
day50 单调栈
数据结构·算法·leetcode
cpp_25017 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25017 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
季明洵7 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi7 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
cpp_25017 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
浅念-7 小时前
C语言编译与链接全流程:从源码到可执行程序的幕后之旅
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
爱吃生蚝的于勒8 小时前
【Linux】进程信号之捕捉(三)
linux·运维·服务器·c语言·数据结构·c++·学习
数智工坊9 小时前
【数据结构-树与二叉树】4.6 树与森林的存储-转化-遍历
数据结构
望舒5139 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode