LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)

素颜马尾好姑娘i 2022-05-08 00:18 256阅读 0赞

题目描述:

给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

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

将其展开为:

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

AC C++ Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. void flatten(TreeNode* root) {
  13. TreeNode* now = root;
  14. while(now) {
  15. if(now->left)
  16. {
  17. TreeNode *pre = now->left;
  18. while(pre->right) {
  19. pre = pre->right;
  20. }
  21. pre->right = now->right; //将当前节点的右子树转接到左子节点的右叶节点上
  22. now->right = now->left; //将当前节点的右子树用左子树代替
  23. now->left = NULL;
  24. }
  25. now = now->right; //遍历下一个节点
  26. }
  27. }
  28. };

类似的:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. void flatten(TreeNode* root) {
  13. while(root) {
  14. if(root->left && root->right) {
  15. TreeNode* t = root->left;
  16. while(t->right)
  17. t = t->right;
  18. t->right = root->right; //将当前节点的右子树接到左子树的右叶节点上
  19. }
  20. if(root->left)
  21. root->right = root->left; //再将当前节点的右子树替换为左子树
  22. root->left = NULL;
  23. root = root->right;
  24. }
  25. }
  26. };

发表评论

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

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

相关阅读