Morris中序遍历
1.用途:将中序遍历的空间复杂度降为O(1)
2.实现:
1 void Morris(root){ 2 struct TreeNode *p = root, *pre = NULL; 3 while (p){ 4 if (!p->left){ //当前结点左子树为空 5 Visit(p); //访问p结点 6 p = p->right; //移动到当前结点的右子树 7 continue; 8 } 9 pre = p->left; //当前结点左子树非空 10 while (pre->right && pre->right != p) pre = pre->right; //pre指向当前结点的前驱结点 11 if (!pre->right){ //把前驱结点链接到当前结点 12 pre->right = p; 13 p = p->left; 14 } else { //断开前驱结点与其后继结点 15 pre->right = NULL; 16 Visit(pre); 17 p = p->right; 18 } 19 } 20 }

浙公网安备 33010602011771号