C++ inorder traversal of binary tree
Your algorithm does seem to work, but it is very complex.  You are pushing nullptr onto the stack when a node has only one child, so you have to check for x != nullptr (which you do),   and if the top of the stack is nullptr (which again, you do).

A better approach would be:


start with an empty vector
start with an empty stack
start with root as the current node
while you are at a valid node, or if the stack is not empty:


if you are at a valid node:


if it has a left child,


push the current node onto the stack
move to the left child.

otherwise (it doesn't have a left child)


append its value to your vector
move to the right child (even if it doesn't exist)


otherwise (you have moved to a nullptr):


pop a node from the stack
append its value to your vector
move to the right child (even if it doesn't exist)




Notice you never push a nullptr onto the stack.  You never need to push a node onto the stack unless you need to return to it.  When you do return to it, you immediately process it by appending its value and moving to its right child.

Also notice that an empty tree is no longer a special case.