leetcode94 二叉树的中序遍历
2023-09-27 14:25:55 时间
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
helper(root, res);
return res;
}
public void helper(TreeNode root, List < Integer > res) {
if(root == null)return;
helper(root.left, res);
res.add(root.val);
helper(root.right, res);
}
}
压栈
public class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}
morris
虽然是空间O(1),但是oj并没有测出来效果,依旧空间只超过40%
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
TreeNode curr = root;
TreeNode pre;
while (curr != null) {
if (curr.left == null) {
res.add(curr.val);
curr = curr.right; // move to next right node
} else { // has a left subtree
pre = curr.left;
while (pre.right != null) { // find rightmost
pre = pre.right;
}
pre.right = curr; // put cur after the pre node
TreeNode temp = curr; // store cur node
curr = curr.left; // move cur to the top of the new tree
temp.left = null; // original cur left be null, avoid infinite loops
}
}
return res;
}
}
相关文章
- 数据结构基础 后序遍历和中序遍历还原二叉树
- leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
- Java实现二叉树及相关遍历方式
- 【算法】【二叉树模块】树的基本先序、中序、后序遍历算法(7种)
- 五三想休息,今天还学习,图解二叉树的层序遍历BFS(广度优先)模板,附面试题题解
- 快速判断二叉树先序遍历 后序遍历
- 二叉树的层序遍历-Python
- 数据结构 有序树转二叉树 (树的遍历)
- 【数据结构】二叉树的概念及结构
- LeetCode 144. 二叉树的前序遍历
- java编写二叉树以及前序遍历、中序遍历和后序遍历 .
- 113、【树与二叉树】leetcode ——538. 把二叉搜索树转换为累加树:递增数组视角右中左遍历(C++版本)
- 102、【树与二叉树】leetcode ——654. 最大二叉树(C++版本)
- 100、【树与二叉树】leetcode ——105. 从前序与中序遍历序列构造二叉树+106. 从中序与后序遍历序列构造二叉树(C++版本)
- 95、【树与二叉树】leetcode ——257. 二叉树的所有路径:递归法DFS/回溯法+迭代法DFS+层序遍历BFS(C++版本)
- 43、【树和二叉树】二叉树的先、中、后和层次遍历方法合集(C/C++版)
- 【二叉树OJ题(二)】前序遍历&&中序遍历&&后序遍历&&另一颗树的子树&&二叉树遍历&&平衡二叉树
- JAVA递归、非递归遍历二叉树(转)
- 【leetcode】103:二叉树的锯齿形层序遍历
- [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历
- LeetCode根据前序与中序、中序与后序,前序与后序遍历序列构建二叉树
- LeetCode二叉树中序遍历
- leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树(中等)