当前位置:网站首页>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/
边栏推荐
- Groeb - "gramm, explicit and complete n -" gramm mask language model, implements the explicit n - "gramm semantic unit modeling knowledge.
- [C语言刷题篇]链表运用讲解
- Exchange the STP/network knowledge
- large number factorial calculation
- 路由ISIS
- [C language brush questions] Explanation of the use of linked lists
- Tutorial/detailed_workflow. Ipynb quantitative financial Qlib library
- Thread Dump分析方法
- Dynamic planning to climb the stairs
- js彩色树叶飘落动画js特效
猜你喜欢
随机推荐
抗HER2/neu受体拟肽修饰的紫杉醇自蛋白纳米粒/环境敏感型多糖纳米粒的制备,
[网络知识]路由OSPF
清道夫受体-A靶向脂肪酸修饰白蛋白纳米粒/银耳多糖修饰白蛋白微球的制备
GBJ2510-ASEMI电机专用25A整流桥GBJ2510
large number factorial calculation
【地形】【虚拟纹理】地形虚拟纹理技术介绍
生物JC TRIM37防止凝集物组织的异位纺锤体极点的形成,以确保有丝分裂的保真度
js选择多张图片对比功能插件
#夏日挑战赛# HarmonyOS - 实现签名功能
浅聊对比学习(Contrastive Learning)
58安全-图像质量评价技术实践
观点:灵魂绑定NFT和去中心化社会
Rust自定义安装路径
Quantitative Finance
58 security - image quality assessment technology practice
js模拟白云慢慢出现js特效
Nuggets quantification: Obtain data through the history method, and use the same proportional weighting factor as Sina Finance and Snowball.different from a flush
面试官:小伙子你来说说MySQL底层架构设计
闻泰科技拟收购欧菲光摄像头业务资产,或将进入苹果供应链!
What is the GMAT test?









