迭代
先
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans=new ArrayList<Integer>();
Stack<TreeNode> stk=new Stack<TreeNode>();
while(root!=null||!stk.isEmpty()){
while(root!=null){
ans.add(root.val);
stk.push(root);
root=root.left;
}
root=stk.pop();
root=root.right;
}
return ans;
}
}
中
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans=new ArrayList<>();
Deque<TreeNode> stk=new LinkedList<>();
while(root!=null||!stk.isEmpty()){
while(root!=null){
stk.push(root);
root=root.left;
}
root=stk.pop();
ans.add(root.val);
root=root.right;
}
return ans;
}
}
后
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null) return ans;
Deque<TreeNode> stk = new LinkedList<TreeNode>();
TreeNode pre = null;
while (root != null || !stk.isEmpty()) {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
if (root.right == null || root.right == pre) {
ans.add(root.val);
pre = root;
root = null;
} else {
stk.push(root);
root = root.right;
}
}
return ans;
}
}
Morris
先
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
while (root != null) {
if (root.left != null) {
TreeNode pre = root.left;
while (pre.right != null && pre.right != root) pre = pre.right;
if (pre.right == null) {
res.add(root.val);
pre.right = root;
root = root.left;
} else {
root = root.right;
}
} else {
res.add(root.val);
root = root.right;
}
}
return res;
}
}
中
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
TreeNode predecessor = null;
while (root != null) {
if (root.left != null) {
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;
}
}
else {
res.add(root.val);
root = root.right;
}
}
return res;
}
}
后
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
TreeNode rt=root;
List<Integer> ans = new ArrayList<Integer>();
if (root == null) return ans;
while (root != null) {
if (root.left != null) {
TreeNode pre = root.left;
while (pre.right != null && pre.right != root) pre=pre.right;
if (pre.right == null) {
pre.right = root;
root = root.left;
} else {
pre.right = null;
addPath(ans, root.left);
root = root.right;
}
}
else {
root = root.right;
}
}
addPath(ans, rt);
return ans;
}
访问一斜行,类似于adidas
public void addPath(List<Integer> ans, TreeNode node) {
int cnt = 0;
while (node != null) {
++cnt;
ans.add(node.val);
node = node.right;
}
int l = ans.size() - cnt, r = ans.size() - 1;
while (l < r) {
int t = ans.get(l);
ans.set(l, ans.get(r));
ans.set(r, t);
l++;
r--;
}
}
}