Flatten Binary Tree to Linked List--LeetCode

太过爱你忘了你带给我的痛 2022-08-07 12:37 136阅读 0赞

题目:

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

For example,
Given

  1. 1
  2. / \
  3. 2 5
  4. / \ \
  5. 3 4 6

The flattened tree should look like:

  1. 1
  2. \
  3. 2
  4. \
  5. 3
  6. \
  7. 4
  8. \
  9. 5
  10. \
  11. 6

思路:从遍历的顺序上是前序遍历的结果,那么使用前序遍历,在前序遍历的过程中改变树结构,对于当前节点,是作为一个新的链表的头部,然后递归调用初始化左子树,递归调用右子树,为了能够连接,还得记住链表的尾部,当前节点的右子树是左子树改造后的链表的头节点,左子树的尾部后端是右子树的头部。

在实现的时候需要注意,最后的连接需要注意查看是否为空的操作。

  1. void helper_list(BinTree*& root,BinTree*& head,BinTree*& tail)
  2. {
  3. if(root == NULL ||(root->right == NULL && root->left == NULL))
  4. {
  5. head = root;
  6. tail = root;
  7. return ;
  8. }
  9. head = root;
  10. BinTree* left_head = root->left;
  11. head->left = NULL;
  12. BinTree* left_tail = NULL;
  13. BinTree* right_head = root->right;
  14. BinTree* right_tail = NULL;
  15. helper_list(left_head,left_head,left_tail);
  16. helper_list(right_head,right_head,right_tail);
  17. if(left_head != NULL)
  18. head->right = left_head;
  19. else
  20. head->right = right_head;
  21. if(left_tail != NULL)
  22. left_tail->right = right_head;
  23. if(right_tail != NULL)
  24. tail = right_tail;
  25. else
  26. tail = left_tail;
  27. }
  28. BinTree* LinkedList(BinTree* root)
  29. {
  30. if(root == NULL)
  31. return NULL;
  32. BinTree * head=NULL,*tail=NULL;
  33. helper_list(root,head,tail);
  34. return head;
  35. }

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读