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

代码如下,开袋即食

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

学生所做,记录学习。

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

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

相关推荐
晚风叙码1 小时前
C++哈希表实现:开放定址法和链地址法 (哈希桶)
数据结构·c++·哈希算法·散列表
imaol11 小时前
哈希表--数据结构
数据结构·散列表
Herbert_hwt16 小时前
C语言零基础入门:循环控制与数据类型详解
c语言·数据结构·算法
晚风醉蝶17 小时前
1-6-插入排序-InsertionSort
java·数据结构·排序算法
Tyler_TXZ17 小时前
C++C语言之——二叉树
c语言·开发语言·数据结构·c++·二叉树
有点。17 小时前
C++二叉树二(练习题)
数据结构·c++·算法·图论
LuminousCPP18 小时前
栈和队列专题(一):LeetCode 20. 有效的括号
数据结构·经验分享·笔记·leetcode·手写栈
白狐_79820 小时前
408 数据结构|线索二叉树两题详解:先序线索化后的空链域 + 中序前驱/后继判断
c语言·数据结构·链表
疯狂打码的少年20 小时前
【数据结构】二叉排序树(BST)的定义与操作
数据结构·笔记·算法
wabs66621 小时前
关于字符串【力扣541.反转字符串II的思考】
数据结构·算法·leetcode·字符串