题意以及限制条件
-
题目:
-
限制条件:
想到的所有可能解法
-
Ways_1——Morris遍历
- 时间复杂度——O(n);空间复杂度——O(1)。
-
Ways_2——递归
- 时间复杂度——O(n);空间复杂度——O(n)。
对应的代码
- Ways_1
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) return res;
TreeNode p1 = root, 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 {
p2.right = null;
res.add(p1.val);
}
} else {
res.add(p1.val);
}
p1 = p1.right;
}
return res;
}
}
- Ways_2