【C++】【LeetCode】114. Flatten Binary Tree to Linked List

题目

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

思路

有两种方法,第一种比较笨,把所有的点按照前序遍历存入队列,然后取出来构建一棵树;还有一种,把左子树的最右叶子节点找到,将右子树作为最右叶子节点的右子树,然后将左子树作为右子树。

代码

思路一
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        if (root == NULL) {
            return ;
        }
        std::queue<TreeNode*> s;
        helper(s, root);
        TreeNode *head = root;
        s.pop();
        while (s.size() > 0) {
            head->right = s.front();
            head->left = NULL;
            head = head->right;
            s.pop();
        }

    }

    void helper(std::queue<TreeNode*>& s, TreeNode* root) {
        if (root == NULL) {
            return;
        }

        s.push(root);
        helper(s, root->left);
        helper(s, root->right);
    }
};
思路二
class Solution {
public:
    void flatten(TreeNode *root) {
        TreeNode*now = root;
        while (now)
        {
            if(now->left)
            {
                //Find current node's prenode that links to current node's right subtree
                TreeNode* pre = now->left;
                while(pre->right)
                {
                    pre = pre->right;
                }
                pre->right = now->right;
                //Use current node's left subtree to replace its right subtree(original right 
                //subtree is already linked by current node's prenode
                now->right = now->left;
                now->left = NULL;
            }
            now = now->right;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值