LeetCode刷题笔记:105.从前序与中序遍历序列构造二叉树

1. 问题描述

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

2. 解题思路

① 通过前序遍历序列的第一个节点可以得到待构造二叉树的根节点。
② 再通过中序遍历序列,由根节点将该序列分为左右两个子树。
③ 递归构建子树。

preorder   	|				|-----------------------|				|--------------------|
		  preL	 		 preL+1           rootIndex-inL+preL  rootIndex-inL+preL+1	    preR	

inorder	 	|--------------------|				|					|--------------------|
		  inL	          rootIndex-1		rootIndex   		rootIndex+1	            inR

3. 实现代码

DFS 中四个 int 类型参数
① preL:前序遍历的起点
② preR:前序遍历的重点
③ inL:中序遍历的起点
④ inR:中序遍历的终点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    HashMap<Integer, Integer> map;
    private TreeNode DFS(int[] preorder, int[] inorder, int preL, int preR, int inL, int inR) {
        if (preL > preR) return null;
        TreeNode root = new TreeNode(preorder[preL]);
        // 根节点在中序遍历中的下标
        int rootIndex = map.get(preorder[preL]);
        int lenLeft = rootIndex - inL; 
        root.left = DFS(preorder, inorder, preL + 1, lenLeft + preL, inL, rootIndex - 1);
        root.right = DFS(preorder, inorder, lenLeft + preL + 1, preR, rootIndex + 1, inR);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len = preorder.length;
        map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            map.put(inorder[i], i);
        }
        return DFS(preorder, inorder, 0, len - 1, 0, len - 1);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值