当前位置:网站首页>LeetCode刷题笔记:105.从前序与中序遍历序列构造二叉树
LeetCode刷题笔记:105.从前序与中序遍历序列构造二叉树
2022-08-03 11:30:00 【LeBron Le】
1. 问题描述
给定两个整数数组 preorder
和 inorder
,其中 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);
}
}
边栏推荐
猜你喜欢
国内数字藏品与国外NFT主要有以下六大方面的区别
【一起学Rust 基础篇】Rust基础——变量和数据类型
完全背包问题的思路解析
CDH6.3.2开启kerberos认证
FR9811S6 SOT-23-6 23V, 2A Synchronous Step-Down DC/DC Converter
字节最爱问的智力题,你会几道?
Binary search tree (search binary tree) simulation implementation (there is a recursive version)
码率vs.分辨率,哪一个更重要?
【一起学Rust】Rust学习前准备——注释和格式化输出
成为优秀架构师必备技能:怎样才能画出让所有人赞不绝口的系统架构图?秘诀是什么?快来打开这篇文章看看吧!...
随机推荐
What is a smart contract?
机器比人更需要通证
Question G: Word Analysis ← Questions for the second provincial competition of the 11th Blue Bridge Cup Competition
记住用户名案例(js)
build --repot
浅谈SVN备份
「全球数字经济大会」登陆 N 世界,融云提供通信云服务支持
【倒计时5天】探索音画质量提升背后的秘密,千元大礼等你来拿
试题G:单词分析 ← 第十一届蓝桥杯大赛第二场省赛赛题
[Star Project] Little Hat Plane Battle (9)
微信小程序获取用户手机号码
3分钟实现内网穿透(基于ngrok实现)
ERC20通证标准是什么?
【JS 逆向百例】某网站加速乐 Cookie 混淆逆向详解
shell编程-测试
html网页如何获取后台数据库的数据(html + ajax + php + mysql)
LeetCode 899 Ordered queue [lexicographical order] HERODING's LeetCode road
一个扛住 100 亿次请求的红包系统,写得太好了!!
ETL data cleaning case in MapReduce
【一起学Rust】Rust包管理工具Cargo初步了解