11/1
the classic inorder traversal, takes O(n) time and O(1) space
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
// The Morris Traversal
List<Integer> ans = new ArrayList<Integer>();
TreeNode p = root;
while(p != null){
if(p.left == null){
ans.add(p.val);
p = p.right;
}else{ // p.left is not null
TreeNode rightM = p.left;
while(rightM.right != null && rightM.right != p){
rightM = rightM.right;
}
if(rightM.right == null){
rightM.right = p;
p = p.left;
}else{
ans.add(p.val);
rightM.right = null;
p = p.right;
}
}
}
return ans;
}
}