Logic is simple, but careful with the details.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode *root) { 13 if (!root) return; 14 flatten(root->left); 15 flatten(root->right); 16 TreeNode *runner = root->left; 17 if (!root->left) return; 18 else { 19 while (runner->right) runner = runner->right; 20 } 21 runner->right = root->right; 22 root->right = root->left; 23 root->left = NULL; 24 } 25 };