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

代码如下,开袋即食

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

学生所做,记录学习。

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

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

相关推荐
AlenTech7 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
会周易的程序员7 小时前
多模态AI 基于工业级编译技术的PLC数据结构解析与映射工具
数据结构·c++·人工智能·单例模式·信息可视化·架构
sin_hielo8 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
一起努力啊~8 小时前
算法刷题-二分查找
java·数据结构·算法
我是小狼君10 小时前
【查找篇章之三:斐波那契查找】斐波那契查找:用黄金分割去“切”数组
数据结构·算法
放荡不羁的野指针10 小时前
leetcode150题-字符串
数据结构·算法·leetcode
bubiyoushang88811 小时前
MATLAB比较SLM、PTS和Clipping三种算法对OFDM系统PAPR的抑制效果
数据结构·算法·matlab
C雨后彩虹11 小时前
计算误码率
java·数据结构·算法·华为·面试
不染尘.12 小时前
进程切换和线程调度
linux·数据结构·windows·缓存
ada7_12 小时前
LeetCode(python)22.括号生成
开发语言·数据结构·python·算法·leetcode·职场和发展