刷题DAY14

题目一

手撕Morris遍历

Morris遍历有啥好处呢 额外空间复杂度只有O(1)

流程 先让cur来到头结点

(1)cur 无左树

直接cur = cur.right

(2)cur 有左树

   1.cur左树的最右节点指向null   最右节点指向cur 然后cur朝左走cur = cur.left 

  2.cur左树的最右节点指向cur  最右节点指向null

public static void Morris(Node head) {
		Node cur = head;
		Node mostright = null;
		while(cur!=null) {
		   mostright = cur.left;
		   if(cur.left!=null) {
			   while(mostright!=null&&mostright!=cur) {
				   mostright = mostright.right;
			   }
			   if(mostright.right==null) {
				   mostright.right = cur;
				   cur = cur.left;
				   continue;
			   }else {
				   mostright.right = null;
			   }
		   }
		   cur = cur.right;
		}
	}

我们只需要记住 每个有左树的点 都会被访问两次 只要抓住这个时机就可以

Morris中序遍历

第一个访问有左树的节点的时候输出

public static void Morrisin(Node head) {
		Node cur = head;
		Node mostright = null;
		while(cur!=null) {
		   mostright = cur.left;
		   if(cur.left!=null) {
			   while(mostright!=null&&mostright!=cur) {
				   mostright = mostright.right;
			   }
			   if(mostright.right==null) {
				   mostright.right = cur;
				   System.out.println(cur.value);
				   cur = cur.left;
				   continue;
			   }else {
				   mostright.right = null;
			   }
		   }
		   cur = cur.right;
		}
	}

Morris前序遍历(第二次来到这个节点的时候输出这个节点)

public static void Morrispre(Node head) {
		Node cur = head;
		Node mostright = null;
		while(cur!=null) {
		   mostright = cur.left;
		   if(cur.left!=null) {
			   while(mostright!=null&&mostright!=cur) {
				   mostright = mostright.right;
			   }
			   if(mostright.right==null) {
				   mostright.right = cur;
				   cur = cur.left;
				   continue;
			   }else {
				   mostright.right = null;
				   System.out.println(cur.value);
			   }
		   }
		   cur = cur.right;
		}
	}

Morris后序遍历

public static void Morrispos(Node head) {
		Node cur = head;
		Node mostright = null;
		while(cur!=null) {
		   mostright = cur.left;
		   if(cur.left!=null) {
			   while(mostright!=null&&mostright!=cur) {
				   mostright = mostright.right;
			   }
			   if(mostright.right==null) {
				   mostright.right = cur;
				   cur = cur.left;
				   continue;
			   }else {
				   mostright.right = null;
				   printEdge(cur.left);
			   }
		   }
		   cur = cur.right;
		}
		printEdge(head);
	}

你可能感兴趣的:(算法,数据结构)