思路:递归
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
flat(root);
}
/* TreeNode *flat(TreeNode *root)
{
if(!root || !root->left && !root->right) return root;
TreeNode *left = flat(root->left);
TreeNode *right = flat(root->right);
TreeNode *rootLeft = root->left, *rootRight = root->right;
root->left = NULL;
if(left != NULL)
{
root->right = rootLeft;
root = left;
}
if(right != NULL)
{
root->right = rootRight;
root = right;
}
return root;
} */
TreeNode *flat(TreeNode *root)
{
if(!root || !root->left && !root->right) return root;
TreeNode *left = root->left;
TreeNode *right = root->right;
root->left = NULL;
if(left != NULL)
{
root->right = left;
root = flat(left);
}
if(right != NULL)
{
root->right = right;
root = flat(right);
}
return root;
}
};