当前位置: 首页 > 文档资料 > LeetCode 题解 >

Tree - Flatten Binary Tree to Linked List

优质
小牛编辑
131浏览
2023-12-01

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. class Solution {
  2. public:
  3. void flatten(TreeNode *root) {
  4. if(!root) {
  5. return;
  6. }
  7. vector<TreeNode*> ns;
  8. TreeNode dummy(0);
  9. TreeNode* n = &dummy;
  10. ns.push_back(root);
  11. while(!ns.empty()) {
  12. TreeNode* p = ns.back();
  13. ns.pop_back();
  14. //挂载到右子树
  15. n->right = p;
  16. n = p;
  17. //右子树压栈
  18. if(p->right) {
  19. ns.push_back(p->right);
  20. p->right = NULL;
  21. }
  22. //左子树压栈
  23. if(p->left) {
  24. ns.push_back(p->left);
  25. p->left = NULL;
  26. }
  27. }
  28. }
  29. };