Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

The flattened tree should look like:

 

 

将一个二叉树变成一个链表形式的二叉树,规则题目没说,要按照样例的规则来。

c++

class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL) return;
dfs(root,root->left,root->right);
root->left=NULL;

}

void dfs(TreeNode* root,TreeNode* a,TreeNode* b)
{
flatten(a);
if(root->right==NULL)
{
root->right = a;
return;
}
if(root->right!=NULL)
{
flatten(b);
if(a!=NULL)
{
join(a,b);
root->right = a;
}
}

}
void join(TreeNode *a,TreeNode *b)
{
if(a->right!=NULL)
join(a->right,b);
else
{
a->right = b;
}
}


};