当前位置:网站首页>leetcode94 -- 二叉树的中序遍历
leetcode94 -- 二叉树的中序遍历
2022-07-29 17:14:00 【Marry Andy】
一、问题描述
给定一个二叉树的根节点root ,返回 它的中序遍历 。
示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
二、解决问题
法一:递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inOrder(root, res);
return res;
}
public void inOrder(TreeNode root, List res){
if(root == null)
return;
inOrder(root.left, res);
res.add(root.val);
inOrder(root.right, res);
}
- 时间复杂度:O(n)
(其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。) - 空间复杂度:O(n)
(空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。)
法二:非递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
- 时间复杂度:O(n)
(其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。) - 空间复杂度:O(n)
(空间复杂度取决于栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。)
法三:Morris 中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans=new LinkedList<>();
while(root!=null){
//没有左子树,直接访问该节点,再访问右子树
if(root.left==null){
ans.add(root.val);
root=root.right;
}else{
//有左子树,找前驱节点,判断是第一次访问还是第二次访问
TreeNode pre=root.left;
while(pre.right!=null&&pre.right!=root)
pre=pre.right;
//是第一次访问,访问左子树
if(pre.right==null){
pre.right=root;
root=root.left;
}
//第二次访问了,那么应当消除链接
//该节点访问完了,接下来应该访问其右子树
else{
pre.right=null;
ans.add(root.val);
root=root.right;
}
}
}
return ans;
}
}
- 时间复杂度:O(n)
(其中 n 为二叉搜索树的节点个数。Morris 遍历中每个节点会被访问两次,因此总时间复杂度为 O(2n)=O(n)。) - 空间复杂度:O(1)
参考:https://leetcode.cn/problems/binary-tree-inorder-traversal/solution/
边栏推荐
猜你喜欢

query词权重, 搜索词权重计算

Thread Dump分析方法

CRM如何帮助企业营销获客

RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment

一键搭建博客:如何使用WordPress插件搭建专属博客

js图片等分对比插件

Tech Talk 活动回顾|基于 Amazon KVS 打造智能视觉产品

Query term weights, search term weighting

Review | Tech Talk activities based on Amazon KVS create intelligent visual products

TweenMax+SVG火箭升空动画js特效
随机推荐
ByteArrayOutputStream class source code analysis
Sentinel热门词汇限流如何实现
Flutter dynamic | Fair server new version features
factorial factorization
生物JC TRIM37防止凝集物组织的异位纺锤体极点的形成,以确保有丝分裂的保真度
中芯国际:禁令后全力自救,设备等待期拉长,但没有客户“离开”
GBJ2510-ASEMI电机专用25A整流桥GBJ2510
HER2-2-ME-BSANPs单抗特异性的2-甲氧基雌二醇白蛋白纳米粒的研究与制备
Flink on yarn双流join问题分析+性能调优思路
query词权重, 搜索词权重计算
hihoCoder#: 博弈游戏·Nim游戏
Sorting and searching binary search method
leetcode:1901. 寻找峰值 II【二分找矩阵局部最大】
How CRM Helps Enterprise Marketing Acquire Customers
大数阶乘计算
pycaret在钻石数据集上的使用 - 回归问题
Pycaret on diamond data sets using the regression problem
【翻译】设备管理器—英特尔网卡属性设置高级选项的功能
(笔记)Build was configured to prefer settings repositories over project repositories but 解决方法
面试官:MySQL如何根据执行计划调优SQL语句?