114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode *firstnode=makeTree(root);
}
TreeNode* makeTree(TreeNode *root)
{
if(root==NULL) return NULL;
else
{
TreeNode* rightnode=root->right; //把右子树保存起来
TreeNode* currentright=makeTree(root->left); //递归左子树
if(currentright!=NULL) root->right=root->left; //左子树非空,让其左子树变成其右子树
else currentright=root;
root->left=NULL; //将左子树置为null
TreeNode* currentnext=makeTree(rightnode);
if (currentnext!=NULL)
{
currentright->right=rightnode; //让当前最后一个节点的右子树指向右子树
return currentnext;
}
else return currentright;
}
}