代码随想录算法训练营Day18|513.找树左下角的值、112. 路径总和、113. 路径总和ii、106.从中序与后序遍历序列构造二叉树

目录

513.找树左下角的值

前言

层序遍历

递归法

[112. 路径总和](#112. 路径总和)

前言

递归法

[113. 路径总和ii](#113. 路径总和ii)

前言

递归法

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

前言

思路

递归法

总结


513.找树左下角的值

题目链接

文章链接

前言

本题要求得到二叉树最后一行最左边的值,使用层序遍历可以较为容易地实现,使用递归法要再次用到回溯对不满足条件的路径进行回退。

层序遍历

cpp 复制代码
/**
 * 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;
        int result = 0;
        if (root == NULL) return result;
        que.push(root);
        vector <int> vec;
        while (!que.empty()){
            int size = que.size();
            vec = {}; //每层遍历都要初始化vec数组
            for (int i = 0; i < size; i++){
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return result = vec[0];
    }
};

因为最终只要获得最后一行的节点数值,所以vec容器每层都要重新初始化进行收集,直到最后一层,此时容器中保存的即为最后一行的节点数值,第一个就是符合条件的左下角的值。

递归法

cpp 复制代码
/**
 * 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 result;
    void traversal(TreeNode* root, int depth){
        if (root->left == NULL && root->right == NULL){ //判断是否为叶子节点
            if (depth > maxDepth){
                maxDepth = depth;
                result = root->val;
            }
            return;
        }

        if (root->left){ //左
            depth++;
            traversal(root->left, depth);
            depth--; //回溯
        }
        if (root->right){ //右
            depth++;
            traversal(root->right,depth);
            depth--; //回溯
        }
        return;
    }

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

由于只需要求最下行最左侧节点,因此在递归遍历时不需要对中节点进行处理,满足最大深度的叶子节点和最左侧的条件才是符合题目要求的。

112. 路径总和

题目链接

文章链接

前言

本题的目的在于更好地理解递归函数什么时候要有返回值,什么时候没有返回值。

在确定递归函数的参数和返回类型时,参数需要二叉树的根节点,还需要一个计数器,这个计数器用来计算二叉树的一条边之和是否正好是目标和,计数器为int型。

递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:

  • 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。
  • 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。
  • 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。

递归法

cpp 复制代码
/**
 * 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 count){
        if (!cur->left && !cur->right && count == 0) return true;
        if (!cur->left && !cur->right) return false;

        if (cur->left){
            count -= cur->left->val;
            if (traversal(cur->left, count)) return true;
            count += cur->left->val; //回溯
        }

        if (cur->right){
            count -= cur->right->val;
            if (traversal(cur->right, count)) return true;
            count += cur->right->val;
        }
        return false;
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        if (root == NULL) return false;
        return traversal(root, targetSum - root->val);
    }
};

掌握本题后,下面一题就好理解了。

113. 路径总和ii

题目链接

文章链接

前言

路径总和ii要遍历整个树,找到所有路径,所以递归函数不要返回值!

递归法

cpp 复制代码
/**
 * 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 {
private:
    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) return;

        if (cur->left){
            path.push_back(cur->left->val); 
            count -= cur->left->val;
            traversal(cur->left, count);
            count += cur->left->val;
            path.pop_back();
        }
        if (cur->right){
            path.push_back(cur->right->val);
            count -= cur->right->val;
            traversal(cur->right, count);
            count += cur->right->val;
            path.pop_back();
        }
        return;
    }

public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        if (root == NULL) return result;
        path.push_back(root->val);
        traversal(root, targetSum - root->val);
        return result;
    }
};

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

题目链接

文章链接

前言

本题要根据两个遍历顺序构造一个唯一的二叉树,整体思路是以后序数组的最后一个元素为切割点,先切中序数组,根据中序数组,反过来再切后序数组。一层一层切下去,每次后序数组最后一个元素就是节点元素。

思路

实现步骤:

  • 第一步:判断数组大小是否为零,为零说明是空节点了;

  • 第二步:如果不为零,那么取后序数组最后一个元素作为根节点元素;

  • 第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点;

  • 第四步:切割中序数组,切成中序左数组和中序右数组 ;

  • 第五步:切割后序数组,切成后序左数组和后序右数组;

  • 第六步:递归处理左区间和右区间

递归法

cpp 复制代码
/**
 * 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 {
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 index;
        for (index = 0; index < inorder.size(); index++){
            if (inorder[index] == rootValue) break;
        } 

        //第四步 切割中序数组 得到 中序左数组和中序右数组
        //左闭右开区间
        vector<int> leftInorder(inorder.begin(), inorder.begin() + index);
        vector<int> rightInorder(inorder.begin() + index + 1, inorder.end());

        //第五步 切割后序数组 得到 后序左数组和后序右数组
        postorder.resize(postorder.size() - 1);

        vector<int>leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
        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) return NULL;
        return traversal(inorder, postorder);
    }
};

要注意切割时边界值的判断。

总结

重点掌握巩固二叉树的递归实现,以及二叉树递归参数及返回值的确定。

相关推荐
集.翔物10 分钟前
hdu-6024
c++·算法
无聊看看天T^T13 分钟前
网络基础:TCP/IP五层模型、数据在局域网传输和跨网络传输的基本流程、IP地址与MAC地址的简单解析
网络·数据结构·c++·网络协议·tcp/ip·算法
通信仿真实验室30 分钟前
(4)MATLAB生成CRC校验码
开发语言·数据结构·matlab
月白风清江有声32 分钟前
关于KKT条件的线性约束下非线性问题-MATLAB
开发语言·算法·matlab
凡人的AI工具箱41 分钟前
《15分钟轻松学 Python》教程目录
开发语言·数据结构·人工智能·python·算法
代码雕刻家1 小时前
课设实验-数据结构-线性表-手机销售
c语言·数据结构
Tonvia1 小时前
猫猫cpu的缓存(NW)
算法·缓存
高一学习c++会秃头吗1 小时前
C++函数指针类型
开发语言·c++·算法
秀聚2 小时前
C++中的类型推导:auto 和 decltype 介绍
数据结构·c++·算法
Inverse1622 小时前
C语言_回调函数和qsort
c语言·数据结构·算法