Complete the code to move to the left child in Morris Traversal.
while (current != null) { if (current.left == null) { Console.Write(current.val + " "); current = current[1]; } else { // Find the inorder predecessor } }
When the left child is null, we print the current node and move to its right child.
Complete the code to find the inorder predecessor in Morris Traversal.
TreeNode predecessor = current.left; while (predecessor.right != null && predecessor.right != current) { predecessor = predecessor[1]; }
The inorder predecessor is the rightmost node in the left subtree, so we move right repeatedly.
Fix the error in setting the temporary link for Morris Traversal.
if (predecessor.right == null) { predecessor.right = current; current = current[1]; }
After setting the temporary link, move to the left child to continue traversal.
Fill both blanks to remove the temporary link and move to the right child.
else { predecessor[1] = null; Console.Write(current.val + " "); current = current[2]; }
Remove the temporary link by setting predecessor.right to null, then move to current.right.
Fill all three blanks to complete the Morris Traversal inorder method.
public void MorrisInorder(TreeNode root) {
TreeNode current = root;
while (current != null) {
if (current.left == null) {
Console.Write(current.val + " ");
current = current[1];
} else {
TreeNode predecessor = current.left;
while (predecessor.right != null && predecessor.right != current) {
predecessor = predecessor[2];
}
if (predecessor.right == null) {
predecessor.right = current;
current = current[3];
} else {
predecessor.right = null;
Console.Write(current.val + " ");
current = current.right;
}
}
}
}This completes the Morris Traversal: move right if no left child, find predecessor by moving right, set temporary link and move left.
