Flatten Binary Tree to Linked List--LeetCode

题目:

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

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6
The 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;
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值