当前位置:网站首页>Sword finger offer 07 Rebuild binary tree
Sword finger offer 07 Rebuild binary tree
2022-06-27 07:27:00 【Yake1965】
The finger of the sword Offer 07. Reconstruction of binary tree
recursive
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0) return null;
TreeNode root = new TreeNode(preorder[0]);
// Question 1 : Find the location of the root node , adopt HashMap solve .
int idx = 0;
for(; idx < inorder.length; idx++){
if(inorder[idx] == preorder[0]) break;
}
// Question two :java Array cannot get subarray , Solve by copying or indexing .
if(idx >= 0){
root.left = this.buildTree(Arrays.copyOfRange(preorder, 1, idx + 1), Arrays.copyOfRange(inorder, 0, idx));
}
if(idx <= preorder.length - 1){
root.right = this.buildTree(Arrays.copyOfRange(preorder, idx + 1, preorder.length), Arrays.copyOfRange(inorder, idx + 1, inorder.length));
}
return root;
}
}
| Root node preamble index | Middle order left boundary | Middle order right boundary | |
|---|---|---|---|
| The left subtree | rootidx + 1 | left | i - 1 |
| Right subtree | rootidx + i - left + 1 | i + 1 | right |
TIPS: i - left + rootidx + 1 It means Root node index + Left subtree length + 1
class Solution {
HashMap<Integer, Integer> d = new HashMap<>(); // Class variables
public TreeNode buildTree(int[] preorder, int[] inorder) {
// In the middle order, the root node divides the left and right subtrees [left, idx), (idx, right)
// It is convenient to obtain the location of the root node
for(int i = 0; i < inorder.length; i++)
d.put(inorder[i], i);
// rootidx = 0, left = 0, right = inorder.length - 1
return recur(preorder, 0, 0, inorder.length - 1);
}
// The root node index is at preorder Middle computation , The scope is inorder Middle computation .
TreeNode recur(int[] preorder, int ridx, int left, int right) {
if(left > right) return null; // Recursive termination
TreeNode node = new TreeNode(preorder[ridx]); // Establish root node
int i = d.get(preorder[ridx]); // The root node divides the left and right subtrees
node.left = recur(preorder, ridx + 1, left, i - 1); // Turn on left subtree recursion
node.right = recur(preorder, ridx + i - left + 1, i + 1, right); // Turn on right subtree recursion
return node;
}
}
iteration
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length, idx = 0; // inorder Indexes
if(preorder == null || n == 0) return null;
TreeNode root = new TreeNode(preorder[0]);
Deque<TreeNode> q = new ArrayDeque<>();
q.push(root);
for(int i = 1; i < n; i++){
// Traverse preorder
int val = preorder[i]; // Antecedent value
TreeNode top = q.peek();
if(top.val != inorder[idx]){
// Construct the left node
top.left = new TreeNode(val);
q.push(top.left);
} else {
while(!q.isEmpty() && q.peek().val == inorder[idx]){
top = q.pop();
idx++; // Traverse inorder
}
top.right = new TreeNode(val); // Construct the right node
q.push(top.right);
}
}
return root;
}
}
边栏推荐
- R language calculates Spearman correlation coefficient in parallel to speed up the construction of co occurrence network
- hutool对称加密
- PostgreSQL encounters permission denied in Windows system
- Visual Studio VS 快捷键使用大全
- Interviewer: how to never migrate data and avoid hot issues by using sub database and sub table?
- poi导出excle
- 请问网页按钮怎么绑定sql语句呀
- 什么是浮选机?
- Park and unpark in unsafe
- postgreSQL在windows系统遇到权限否认(permission denied)
猜你喜欢
![[Kevin's third play in a row] is rust really slower than C? Further analyze queen micro assessment](/img/ac/44e0ecd04fbea5efd39d2cc75dea59.jpg)
[Kevin's third play in a row] is rust really slower than C? Further analyze queen micro assessment

云服务器配置ftp、企业官网、数据库等方法

SQL injection bypass (I)

用XGBoost迭代读取数据集

一個人管理1000臺服務器?這款自動化運維工具一定要掌握

面试官:你天天用 Lombok,说说它什么原理?我竟然答不上来…

从5秒优化到1秒,系统飞起来了...

Configuring FTP, enterprise official website, database and other methods for ECS

Rust Async: smol源码分析-Executor篇

VNC Viewer方式的远程连接树莓派
随机推荐
面试官:用分库分表如何做到永不迁移数据和避免热点问题?
pytorch Default process group is not initialized
Jupiter notebook file directory
vs怎么配置OpenCV?2022vs配置OpenCV详解(多图)
一個人管理1000臺服務器?這款自動化運維工具一定要掌握
语音信号处理-概念(二):幅度谱(短时傅里叶变换谱/STFT spectrum)、梅尔谱(Mel spectrum)【语音的深度学习主要用幅度谱、梅尔谱】【用librosa或torchaudio提取】
攻防演习防御体系构建之第一篇之介绍和防守的四个阶段
在线文本数字识别列表求和工具
再见了,敏捷Scrum
JDBC reads MySQL data list
guava 教程收集一些案例慢慢写 google工具类
【编译原理】山东大学编译原理复习提纲
[openairinterface5g] rrcsetupcomplete for RRC NR resolution
How torch.gather works
Rust Async: smol源码分析-Executor篇
JDBC事务提交事例
Interviewer: please introduce cache penetration, cache null value, cache avalanche and cache breakdown, which are easy to understand
Coggle 30 Days of ML 7月竞赛学习
(已解决) npm突然报错 Cannot find module ‘D:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js‘
Apifox learning