Link the tree with right in the order of traversal in the forward order.
I thought for a long time, but I didn't have any idea at all. I always thought that the inplace solution was very clever.
Later, I decided to use a variable to record the current access point. It was so witty ~~
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 now = NULL;14 findRes(root);15 }16 private:17 TreeNode * now;18 void findRes(TreeNode *root) {19 if (root == NULL) {20 return;21 }22 findRes(root->right);23 findRes(root->left);24 root->left = NULL;25 root->right = now;26 now = root;27 }28 };
After an AC, I read the question and found that the ideas differ greatly! The version of iteration is clear. Once again, it is also an AC.
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 == NULL) {14 return;15 }16 stack<TreeNode*> s;17 s.push(root);18 while (!s.empty()) {19 TreeNode * now = s.top();20 s.pop();21 if (now->right != NULL) {22 s.push(now->right);23 }24 if (now->left != NULL) {25 s.push(now->left);26 }27 now->left = NULL;28 if (!s.empty()) {29 now->right = s.top();30 }31 }32 }33 };