题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
在实现的时候需要注意,最后的连接需要注意查看是否为空的操作。
void helper_list(BinTree*& root,BinTree*& head,BinTree*& tail)
{
if(root == NULL ||(root->right == NULL && root->left == NULL))
{
head = root;
tail = root;
return ;
}
head = root;
BinTree* left_head = root->left;
head->left = NULL;
BinTree* left_tail = NULL;
BinTree* right_head = root->right;
BinTree* right_tail = NULL;
helper_list(left_head,left_head,left_tail);
helper_list(right_head,right_head,right_tail);
if(left_head != NULL)
head->right = left_head;
else
head->right = right_head;
if(left_tail != NULL)
left_tail->right = right_head;
if(right_tail != NULL)
tail = right_tail;
else
tail = left_tail;
}
BinTree* LinkedList(BinTree* root)
{
if(root == NULL)
return NULL;
BinTree * head=NULL,*tail=NULL;
helper_list(root,head,tail);
return head;
}