1、二叉树的前序遍历(Morris)
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
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) {
ans.add(p1.val);
p2.right = p1;
p1 = p1.left;
continue;
} else {
p2.right = null;
}
} else {
ans.add(p1.val);
}
p1 = p1.right;
}
return ans;
}
}
2、二叉树的中序遍历(Morris)
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
TreeNode p1 = root, p2 = null;
while(p1 != null) {
p2 = p1.left;
if(p1.left != null) {
while(p2.right != null && p2.right != p1) {
p2 = p2.right;
}
if(p2.right != null) {
p2.right = null;
ans.add(p1.val);
p1 = p1.right;
} else {
p2.right =p1;
p1 = p1.left;
}
} else {
ans.add(p1.val);
p1 = p1.right;
}
}
return ans;
}
}
3、二叉树的后序遍历(Morris)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root == null) return ans;
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(ans, p1.left);
}
}
p1 = p1.right;
}
addPath(ans, root);
return ans;
}
private void addPath(List<Integer> ans, TreeNode node) {
int count = 0;
while(node != null) {
ans.add(node.val);
node = node.right;
count++;
}
int left = ans.size() - count, right = ans.size() - 1;
while(left < right) {
int tmp = ans.get(left);
ans.set(left, ans.get(right));
ans.set(right, tmp);
left++;
right--;
}
}
}
4、二叉树的后序非递归
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Deque<TreeNode> stack = new LinkedList<>();
TreeNode pre = null;
while(root != null || !stack.isEmpty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right == null || root.right == pre) {
ans.add(root.val);
pre = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return ans;
}
}