当前位置:网站首页>来n遍剑指--07. 重建二叉树
来n遍剑指--07. 重建二叉树
2022-07-31 08:57:00 【秦 羽】
专栏前言:
本专栏主要是算法训练,目的很简单。在掌握基本的java知识后,学习最重要的算法知识,在学习之前首先要对自身有一定的理解,如果不知道怎么做欢迎来私聊。
算法的过程很枯燥,但是也很特别,不断地刷题,不断地分享才会越来越好,给别人讲明白才是真正学会了。在分享中学会知识。
坚持就是胜利~~~
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
限制:
0 <= 节点个数 <= 5000
解题1:
这个问题我将思路写在了下方,多练熟记
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length == 0){
return null;
}
//根节点
TreeNode root = new TreeNode(preorder[0]);
Deque<TreeNode> stack = new LinkedList<>();
//将根节点推入栈中
stack.push(root);
//定义一个中序遍历下标
int inorderIndex = 0;
//循环前序遍历
for(int i = 1; i < preorder.length; ++i){
//前序遍历的值
int preorderVal = preorder[i];
//找到栈顶值
TreeNode node = stack.peek();
//如果栈顶的值不等于 中序遍历的第一个值
if(node.val != inorder[inorderIndex]){
//那么该值就是根节点的左孩子,将左孩子推入栈中
node.left = new TreeNode(preorderVal);
stack.push(node.left);
}else{
while(!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]){
node = stack.pop();
inorderIndex++;
}
node.right = new TreeNode(preorderVal);
stack.push(node.right);
}
}
return root;
}
}
课后习题:
| 序号 | 题目链接 | 难度评级 |
|---|---|---|
| 1 | 105. 从前序与中序遍历序列构造二叉树 | 中等 |

边栏推荐
- 关于Error EPERM operation not permitted, mkdir...几种解决办法的比较
- 【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
- SSM整合案例分析(详解)
- Flutter Paystack implements all options
- 【小程序专栏】总结uniapp开发小程序的开发规范
- SQL连接表(内连接、左连接、右连接、交叉连接、全外连接)
- [Yellow ah code] Introduction to MySQL - 3. I use select, the boss directly drives me to take the train home, and I still buy a station ticket
- SQL join table (inner join, left join, right join, cross join, full outer join)
- 【云原生与5G】微服务加持5G核心网
- SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
猜你喜欢
随机推荐
[Cloud native and 5G] Microservices support 5G core network
奉劝那些刚参加工作的学弟学妹们:要想进大厂,这些核心技能是你必须要掌握的!完整学习路线!
ecshop安装的时候提示不支持JPEG格式
期刊投递时的 Late News Submission 是什么
TypeError The view function did not return a valid response. The function either returned None 的解决
【小程序专栏】总结uniapp开发小程序的开发规范
[MySQL exercises] Chapter 2 Basic operations of databases and data tables
服务器上解压文件时提示“gzip: stdin: not in gzip format,tar: Child returned status 1,tar: Error is not recovera“
(selenium)Service geckodriver unexpectedly exited. Status code was: 64
【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)
六、MFC文档类(单文档和多文档)
mysql 数据去重的三种方式[实战]
Which strings will be parsed as null by FastJson?
Kotlin 优点
【Unity】编辑器扩展-02-拓展Hierarchy视图
【MySQL功法】第3话 · MySQL中常见的数据类型
MySQL安装教程
SSM framework explanation (the most detailed article in history)
期刊会议排名、信息检索网站推荐以及IEEE Latex模板下载
功能强大的国产Api管理工具







![[MySQL exercises] Chapter 5 · SQL single table query](/img/11/66b4908ed8f253d599942f35bde96a.png)

