623 在二叉树中增加一行


深度遍历,就是遍历:
1.先要确定有几种情况,像这道题,深度为1,2就是最基本的情况,分为两种处理;
2.根据不同情况,进行不同处理,不需要考虑后面递归的传递。
3.确认传递的方式,如果函数返回的是指针,就需要left,right接住。
完整代码:

点击查看代码
class Solution {
public:
    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        if (root == nullptr) {
            return nullptr;
        }
        if (depth == 1) {
            return new TreeNode(val, root, nullptr);
        }
        if (depth == 2) {
            root->left = new TreeNode(val, root->left, nullptr);
            root->right = new TreeNode(val, nullptr, root->right);
        } else {
            root->left = addOneRow(root->left, val, depth - 1);
            root->right = addOneRow(root->right, val, depth - 1);
        }
        return root;
    }
};

广度遍历,就可以针对某一层进行处理: leetcode中提到了两个重要函数,emplace_back,move; emplace_back 是 std::vector 类的一个成员函数,它用于在向量的末尾直接构造和插入一个新元素。这个方法通常比 push_back 更高效,特别是在插入的对象是非基本数据类型(如自定义类或结构体)时。 move 本身不移动任何东西。它只是将左值转换为右值引用,使得对象可以作为移动来源。相当于换个名字。 完整代码:
点击查看代码
class Solution {
public:
    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        if (depth == 1) {
            return new TreeNode(val, root, nullptr);
        }
        vector<TreeNode *> curLevel(1, root);
        for (int i = 1; i < depth - 1; i++) {
            vector<TreeNode *> tmpt;
            for (auto &node : curLevel) {
                if (node->left != nullptr) {
                    tmpt.emplace_back(node->left);
                }
                if (node->right != nullptr) {
                    tmpt.emplace_back(node->right);
                }
            }
            curLevel = move(tmpt);
        }
        for (auto &node : curLevel) {
            node->left = new TreeNode(val, node->left, nullptr);
            node->right = new TreeNode(val, nullptr, node->right);
        }
        return root;
    }
};


posted @ 2024-02-12 21:18  yun-che  阅读(20)  评论(0)    收藏  举报