LeetCode 热题 HOT 100 Java题解
94. 二叉树的中序遍历
题目:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
迭代中序遍历
迭代的思想就是构造一个栈,模拟递归的操作,遍历左边的时候,把一路上的节点存入栈,左边到头后,从栈中取出,加入结果集合后再遍历右边。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
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 ) O(n) O(n)
每个节点被访问一次。
-
空间复杂度: O ( n ) O(n) O(n)
最差情况下递归栈大小 O ( n ) O(n) O(n)。
Morris中序遍历
Morris 遍历算法整体步骤如下(假设当前遍历到的节点为 x):
- 如果 x x x 无左孩子,先将 x x x 的值加入答案数组,再访问 x x x 的右孩子,即 x = x . r i g h t x=x.right x=x.right。
- 如果
x
x
x 有左孩子,则找到
x
x
x 左子树上最右的节点(即左子树中序遍历的最后一个节点,
x
x
x 在中序遍历中的前驱节点),我们记为
p
r
e
d
e
c
e
s
s
o
r
predecessor
predecessor。根据
p
r
e
d
e
c
e
s
s
o
r
predecessor
predecessor 的右孩子是否为空,进行如下操作。
- 如果 p r e d e c e s s o r predecessor predecessor 的右孩子为空,则将其右孩子指向 xx,然后访问 x x x 的左孩子,即 x = x . l e f t x=x.left x=x.left。
- 如果 p r e d e c e s s o r predecessor predecessor 的右孩子不为空,则此时其右孩子指向 x x x,说明我们已经遍历完 x x x 的左子树,我们将 p r e d e c e s s o r predecessor predecessor 的右孩子置空,将 x x x 的值加入答案数组,然后访问 x x x 的右孩子,即 x = x . r i g h t x=x.right x=x.right。
- 重复上述操作,直至访问完整棵树。
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
while(root != null) {
if (root.left == null) {
res.add(root.val);
root = root.right;
}
else {
TreeNode predecessor = root.left;
while(predecessor.right != null && predecessor.right != root) predecessor = predecessor.right;
if (predecessor.right == null) {
predecessor.right = root;
root = root.left;
}else {
res.add(root.val);
predecessor.right = null;
root = root.right;
}
}
}
return res;
}
}
复杂度分析
-
时间复杂度: O ( n ) O(n) O(n)
每个节点被访问一次。
-
空间复杂度: O ( 1 ) O(1) O(1)
利用二叉树中的空指针,不需要额外空间。