use stack to implement pre-order traversal, straight-forward solution.

void flatten(TreeNode* root) { stack<TreeNode*> s; if (root) s.push(root); TreeNode dummy(0); TreeNode* tail = &dummy; while (!s.empty()) { TreeNode* now = s.top(); s.pop(); if(now->right) s.push(now->right); if(now->left) s.push(now->left); tail->right = now; tail->left = NULL; tail = tail->right; } }