/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return TreeNode类
     */
    vector<TreeNode*> res;
    void dfs(TreeNode *root){
        if (root == NULL) {
            return ;
        }
        res.push_back(root);
        dfs(root->left);
        dfs(root->right);
    }
    TreeNode* expandTree(TreeNode* root) {
        // write code here
        if(root == NULL) return root;
        dfs(root);
        int n = res.size();
        TreeNode *ans = res[0];
        for (int i = 1; i < n; i++) {
            ans = res[i];
            root->right = ans;
            root->left = NULL;
            root = root->right;
        }
        return root;
    }
};

算法基本思想:

首先对原树进行先序遍历,将遍历结果存储在一个数组中。然后从数组中依次取出节点,将其作为右子节点插入到上一个节点的右子树上,左子树置为空。最后返回根节点即可。

时间复杂度:

遍历整棵树需要 O(n)的时间,插入节点的过程需要O(n)的时间,因此总时间复杂度为O(n)。

空间复杂度:

需要一个vector数组来存储遍历结果,因此空间复杂度为O(n)。