题目
中序遍历打印出二叉树。
递归方法:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
inorder(root,list);
return list;
}
public void inorder(TreeNode root,List<Integer> list){
if(root == null) return;
if(root.left!=null) inorder(root.left,list);
list.add(root.val);
if(root.right!=null) inorder(root.right,list);
}
}
为了使空间复杂度为O(1),采用morris遍历:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
TreeNode cur = root;
TreeNode mright = null;
while(cur != null){
mright = cur.left;
if(mright!=null){
while(mright.right!=null & mright.right!=cur){
mright = mright.right;
}
if(mright.right==null){
mright.right = cur;
cur = cur.left;
continue;
}
else{
mright.right = null;
}
}
list.add(cur.val);
cur = cur.right;
}
return list;
}
}
具体的原理解释,看左神的书p116。