LeetCode_Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

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
按照题目的要求,实际上是要把一个二叉树转换成用右儿子指针相链接的链表,我自己的解法是递归:

即对于节点r,首先实现r的左子树的结构改造,然后将其替换右子树,在将右子树链在最右侧的节点上,代码如下:

  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };
 
class Solution {
public:
    /*void flatten(TreeNode *root) {
       root=FlattenTree(root); 
    }
    TreeNode *FlattenTree(TreeNode *root){
        if(root==NULL){
            return NULL;
        }
        TreeNode *right=root->right;
        root->right=FlattenTree(root->left);
        root->left=NULL;
        TreeNode *temp=root;
        while (temp->right!=NULL){
            temp=temp->right;
        }
        temp->right=FlattenTree(right);
        return root;
    }*/
    void flatten(TreeNode* root) {

        if (!root) return;

        TreeNode* node = root;
        while (node) {

            // Attatches the right sub-tree to the rightmost leaf of the left sub-tree:
            if (node->left) {

                TreeNode *rightMost = node->left;
                while (rightMost->right) {

                    rightMost = rightMost->right;
                }
                rightMost->right = node->right;

                // Makes the left sub-tree to the right sub-tree:
                node->right = node->left;
                node->left = nullptr;
            }

            // Flatten the rest of the tree:
            node = node->right;
        }    
    }
};
注释部分是我自己提交的代码,虽然也AC了,但是使用递归,算法的时空复杂度都不是最优的,后来使用的代码是在Discuss中别人的,巧妙的将递归转换为迭代。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值