class Solution { public: //目的是将binary tree变成前序遍历的list,但是变换过程是后序遍历 void flatten(TreeNode *root, TreeNode *&first, TreeNode *&last){ if (!root) return ; TreeNode *leftFirst = NULL; TreeNode *leftLast = NULL; TreeNode *rightFirst = NULL; TreeNode *rightLast = NULL; flatten(root->left, leftFirst, leftLast); //对于向下调用问题,递归的先处理子树 flatten(root->right, rightFirst, rightLast); //对于向下调用问题,递归的先处理子树 first = root; //对于向上返回问题,first肯定是root if (root->right) //如果有右子树 last = rightLast; else if (root->left) //没有右子树但是有左子树 last = leftLast; else //没有子树 last = root; root->left = NULL; if (leftFirst && !rightFirst){ root->right = leftFirst; } else if (!leftFirst && rightFirst){ root->right = rightFirst; } else if (leftFirst && rightFirst){ root->right = leftFirst; leftLast->right = rightFirst; } else{ root->right = NULL; } } void flatten(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root) return ; TreeNode *first; TreeNode *last; flatten(root, first, last); } };
EOF