力扣hot100学习记录(十二)

94. 二叉树的中序遍历

给定一个二叉树的根节点 root,返回它的中序遍历。
在这里插入图片描述
题意
给定一个二叉树,返回它的中序遍历
思路
采用递归的思想,只要根节点不为空,则一直递归遍历左子树,然后将根节点的值存入结果,最后递归遍历右子树。
代码

class Solution {
public:
    vector<int> ans;
    vector<int> inorderTraversal(TreeNode* root) {
        dfs(root);
        return ans;
    }
    void dfs(TreeNode* root){
        if(!root) return;
        dfs(root->left);
        ans.push_back(root->val);
        dfs(root->right);
    }
};

104. 二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。
二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。
在这里插入图片描述
题意
给定一个二叉树,返回二叉树的最大深度
思路
利用dfs遍历,当节点不为空时,遍历其左子树和右子树,每次的结果为左子树的最大长度和右子树的最大长度的最大值加1
代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        return max(maxDepth(root->left),maxDepth(root->right)) + 1;
    }
};

226. 翻转二叉树

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
在这里插入图片描述

题意
将二叉树沿着根节点翻转
思路
先将根节点的两棵子树交换,在将两棵子树翻转
代码

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return NULL;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-10 07:16:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-10 07:16:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-10 07:16:03       82 阅读
  4. Python语言-面向对象

    2024-06-10 07:16:03       91 阅读

热门阅读

  1. IO流(字符流)

    2024-06-10 07:16:03       32 阅读
  2. Web前端炒作:揭秘行业现象,探索真实价值

    2024-06-10 07:16:03       23 阅读
  3. QT学习之自定义控件封装

    2024-06-10 07:16:03       25 阅读
  4. Python降维基础知识:深入探索与实战应用

    2024-06-10 07:16:03       36 阅读
  5. IDM究竟有哪些优势

    2024-06-10 07:16:03       28 阅读
  6. 快速修改验证Sepolicy(Selinux)

    2024-06-10 07:16:03       33 阅读
  7. 浅谈什么是Google GKE?Auto Pilot模式是什么?

    2024-06-10 07:16:03       28 阅读
  8. 4、Spring之Bean生命周期~获取Bean

    2024-06-10 07:16:03       24 阅读
  9. DeepSpeed入门

    2024-06-10 07:16:03       25 阅读
  10. 使用GoAccess分析nginx日志

    2024-06-10 07:16:03       33 阅读
  11. 亿图图示使用教程

    2024-06-10 07:16:03       33 阅读