力扣 - 94. 二叉树的中序遍历
题目
思路1(递归)
- 中序先遍历左孩子,然后父节点,然后右孩子
- 递归遍历
代码
class Solution {
List<Integer> res = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inOrder(root);
return res;
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
res.add(root.val);
inOrder(root.right);
}
}
复杂度分析
- 时间复杂度:\(O(N)\)
- 空间复杂度:\(O(N)\)
思路2(迭代)
- 用栈遍历
代码
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
Deque<TreeNode> stack = new LinkedList<>();
while (!stack.isEmpty() || root != null) {
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)\)
思路3(Morris遍历)
- 和前序的Morris基本一样,只是在
p2.right == null
中的res.add(p1.val);
被移动到了p2.right != null
中
代码
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode p1 = root;
TreeNode p2 = null;
while (p1 != null) {
p2 = p1.left;
if (p2 != null) {
while (p2.right != null && p2.right != p1) {
p2 = p2.right;
}
if (p2.right == null) {
p2.right = p1;
p1 = p1.left;
continue;
} else {
res.add(p1.val);
p2.right = null;
}
} else {
res.add(p1.val);
}
p1 = p1.right;
}
return res;
}
}
复杂度分析
- 时间复杂度:\(O(N)\),其中 N 为二叉树的结点数
- 空间复杂度:\(O(1)\)
我走得很慢,但我从不后退!