题意以及限制条件
-
题目:
-
限制条件:
想到的所有可能解法
-
Ways_1——Morris遍历
- 时间复杂度——O(n);空间复杂度——O(1)。
-
Ways_2——递归
- 时间复杂度——O(n);空间复杂度——O(n)。
对应的代码
- Ways_1
class Solution {
public List<Integer> postorderTraversal(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;
addPath(res, p1.left);
}
}
p1 = p1.right;
}
addPath(res, root);
return res;
}
public void addPath(List<Integer> res, TreeNode node) {
int count = 0;
while (node != null) {
++count;
res.add(node.val);
node = node.right;
}
int left = res.size() - count, right = res.size() - 1;
while (left < right) {
int temp = res.get(left);
res.set(left++, res.get(right));
res.set(right--, temp);
}
}
}
- Ways_2