「代码随想录算法训练营」第十四天 | 二叉树 part4

513. 找树左下角的值

题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
题目难度:中等
文章讲解:https://programmercarl.com/0513.找树左下角的值.html
视频讲解:https://www.bilibili.com/video/BV1424y1Z7pn
题目状态:有点思路,但未通过,最后在ChatGPT的帮助下理清了思路,顺利通过

思路:

使用层序遍历的思想,每次遍历到一层时,记录这一层的第一个节点的值,当遍历完整个树之后,记录的就是最后一层的第一个节点的值。

代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode *> que;
        if(root == nullptr) return 0;
        int res = root->val;
        que.push(root);
        while(!que.empty()) {
            int size = que.size();
            for(int i = 0; i < size; ++i) {
                TreeNode *node = que.front();
                que.pop();
                if(i == 0) res = node->val;
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
        }
        return res;
    }
};

递归法:递归到每一层时,判断该层是否为最底层,若是,则记录其层第一个节点的值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth = INT_MIN;
    int res;
    void traversal(TreeNode *cur, int depth) {
        if(cur->left == nullptr && cur->right == nullptr) {
            if(depth > maxDepth) {
                maxDepth = depth;
                res = cur->val;
            }
            return;
        }
        if(cur->left) {
            depth++;
            traversal(cur->left, depth);
            depth--;
        }
        if(cur->right) {
            depth++;
            traversal(cur->right, depth);
            depth--;
        }
        return;
    }

    int findBottomLeftValue(TreeNode* root) {
        traversal(root, 0);
        return res;
    }
};

112. 路径总和

题目链接:https://leetcode.cn/problems/path-sum/
题目难度:简单
文章讲解:https://programmercarl.com/0112.路径总和.html
视频讲解:https://www.bilibili.com/video/BV19t4y1L7CR
题目状态:没思路,回溯+递归靠自己还是想不起来

思路:

使用递归+回溯的方法。

  1. 递归参数和返回值:参数是二叉树节点cur和目标target,目标用来进行--的,每遍历到一个节点时,用target减去其值,若到叶子节点时,target的值为 0,表示找到了这条路径是target的总和,返回值是bool
  2. 终止条件:当该节点为叶子节点且当前target为 0 时,返回true,表示找到了这个路径;若该节点为叶子节点但target值不为 0,表示没找到,返回false
  3. 单个循环思路:当遍历到该节点是,将target减去其值,若其有左孩子,target减去左孩子值,并递归到左孩子,其左孩子将会向下遍历,若找到了一个路径,将返回true给它的父节点,依次向上循环,直到结束递归;右孩子的递归是和左孩子一样的。

代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool traversal(TreeNode *cur, int target) {
        if(cur->left == nullptr && cur->right == nullptr && target == 0) return true;
        if(cur->left == nullptr && cur->right == nullptr && target != 0) return false;
        if(cur->left) {
            target -= cur->left->val;
            if(traversal(cur->left, target)) return true;
            target += cur->left->val;
        }
        if(cur->right) {
            target -= cur->right->val;
            if(traversal(cur->right, target)) return true;
            target += cur->right->val;
        }
        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        return traversal(root, targetSum - root->val);
    }
};

113. 路径总和II

题目链接:https://leetcode.cn/problems/path-sum-ii/
题目难度:中等
文章讲解:https://programmercarl.com/0112.路径总和.html#相关题目推荐
题目状态:诶,还是没写出来

思路:

和上题一样,使用递归+回溯,但是自己想还是想不起来,在递归中将路径记录下来,最后判定终止条件时将路径压入到结果中。

代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> result;
    vector<int> path;
    void traversal(TreeNode *cur, int count) {
        if(!cur->left && !cur->right && count == 0) {
            result.push_back(path);
            return;
        }
        if(!cur->left && !cur->right && count != 0) return;
        if(cur->left) {
            count -= cur->left->val;
            path.push_back(cur->left->val);
            traversal(cur->left, count);
            count += cur->left->val;
            path.pop_back();
        }
        if(cur->right) {
            count -= cur->right->val;
            path.push_back(cur->right->val);
            traversal(cur->right, count);
            count += cur->right->val;
            path.pop_back();
        }
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        result.clear();
        path.clear();
        if(root == nullptr) return result;
        path.push_back(root->val);
        traversal(root, targetSum - root->val);
        return result;
    }
};

106. 从中序与后序遍历序列构造二叉树

题目链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目难度:中等
文章讲解:https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html
视频讲解:https://www.bilibili.com/video/BV1vW4y1i7dn
题目状态:太难了,没有思路

思路:

递归:

  1. 如果数组大小为零的话,说明是空节点了。
  2. 如果不为空,那么取后序数组最后一个元素作为节点元素。
  3. 找到后序数组最后一个元素在中序数组的位置,作为切割点。
  4. 切割中序数组,切成中序左数组和中序右数组(顺序别搞反了,一定是先切中序数组)。
  5. 切割后序数组,切成后序左数组和后序右数组。
  6. 递归处理左区间和右区间。

代码实现:

class Solution {
private:
    TreeNode* traversal (vector<int>& inorder, vector<int>& postorder) {
        if (postorder.size() == 0) return NULL;

        // 后序遍历数组最后一个元素,就是当前的中间节点
        int rootValue = postorder[postorder.size() - 1];
        TreeNode* root = new TreeNode(rootValue);

        // 叶子节点
        if (postorder.size() == 1) return root;

        // 找到中序遍历的切割点
        int delimiterIndex;
        for (delimiterIndex = 0; delimiterIndex < inorder.size(); delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }

        // 切割中序数组
        // 左闭右开区间:[0, delimiterIndex)
        vector<int> leftInorder(inorder.begin(), inorder.begin() + delimiterIndex);
        // [delimiterIndex + 1, end)
        vector<int> rightInorder(inorder.begin() + delimiterIndex + 1, inorder.end());

        // postorder 舍弃末尾元素
        postorder.resize(postorder.size() - 1);

        // 切割后序数组
        // 依然左闭右开,注意这里使用了左中序数组大小作为切割点
        // [0, leftInorder.size)
        vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
        // [leftInorder.size(), end)
        vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end());

        root->left = traversal(leftInorder, leftPostorder);
        root->right = traversal(rightInorder, rightPostorder);

        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return NULL;
        return traversal(inorder, postorder);
    }
};

105. 从前序与中序遍历序列构造二叉树

题目链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题目难度:中等
文章讲解:https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html#相关题目推荐
题目状态:独立搓不出来

思路:

和上一题大同小异。

代码实现:

class Solution {
private:
        TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& preorder, int preorderBegin, int preorderEnd) {
        if (preorderBegin == preorderEnd) return NULL;

        int rootValue = preorder[preorderBegin]; // 注意用preorderBegin 不要用0
        TreeNode* root = new TreeNode(rootValue);

        if (preorderEnd - preorderBegin == 1) return root;

        int delimiterIndex;
        for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
            if (inorder[delimiterIndex] == rootValue) break;
        }
        // 切割中序数组
        // 中序左区间,左闭右开[leftInorderBegin, leftInorderEnd)
        int leftInorderBegin = inorderBegin;
        int leftInorderEnd = delimiterIndex;
        // 中序右区间,左闭右开[rightInorderBegin, rightInorderEnd)
        int rightInorderBegin = delimiterIndex + 1;
        int rightInorderEnd = inorderEnd;

        // 切割前序数组
        // 前序左区间,左闭右开[leftPreorderBegin, leftPreorderEnd)
        int leftPreorderBegin =  preorderBegin + 1;
        int leftPreorderEnd = preorderBegin + 1 + delimiterIndex - inorderBegin; // 终止位置是起始位置加上中序左区间的大小size
        // 前序右区间, 左闭右开[rightPreorderBegin, rightPreorderEnd)
        int rightPreorderBegin = preorderBegin + 1 + (delimiterIndex - inorderBegin);
        int rightPreorderEnd = preorderEnd;

        root->left = traversal(inorder, leftInorderBegin, leftInorderEnd,  preorder, leftPreorderBegin, leftPreorderEnd);
        root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, preorder, rightPreorderBegin, rightPreorderEnd);

        return root;
    }

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (inorder.size() == 0 || preorder.size() == 0) return NULL;

        // 参数坚持左闭右开的原则
        return traversal(inorder, 0, inorder.size(), preorder, 0, preorder.size());
    }
};
posted @ 2024-07-18 15:45  云雀AC了一整天  阅读(7)  评论(0编辑  收藏  举报