树的遍历
先序遍历(preorder traversal):自己–左子树–右子树
中序遍历(inorder traversal):左子树–自己–右子树
后序遍历(postorder traversal):左子树–右子树–自己
morris遍历
时间复杂度(time complexity): O(n)
空间复杂度(space complexity): O(1)
中序遍历:
public indorMorris(TreeNode root) {
List<Integer> nums=new ArrayList<Integer>();
TreeNode cur=root,tmp=root;
while(cur!=null) {
if(cur.left!=null) {
tmp=cur.left;
while(tmp.right!=null&&tmp.right!=cur)
tmp=tmp.right;
if(tmp.right==null) {
tmp.right=cur;
cur=cur.left;
}else {
nums.add(cur.val);
cur=cur.right;
}
}else {
nums.add(cur.val);
cur=cur.right;
}
}
}
- nums数组用于记录遍历的结果
- 外循环条件是判断当前节点cur是否为空,初始时当前节点为根节点
https://blog.csdn.net/zuochao_2013/article/details/78538729
https://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html