(LeetCode 面试经典 150 题) 104. 二叉树的最大深度 (深度优先搜索dfs)

题目:104. 二叉树的最大深度

思路:深度优先搜索dfs,时间复杂度0(n)。

C++版本:

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(TreeNode* root) {
        if(root==nullptr) return 0;
        int left=maxDepth(root->left);
        int right=maxDepth(root->right);
        return max(left,right)+1;
    }
};## 标题

JAVA版本:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        int left=maxDepth(root.left);
        int right=maxDepth(root.right);
        return Math.max(left,right)+1;
    }
}

GO版本:

go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root==nil {return 0}
    left:=maxDepth(root.Left)
    right:=maxDepth(root.Right)
    return max(left,right)+1
}
相关推荐
nice_lcj5204 小时前
MySQL 的锁:行锁、表锁、间隙锁与死锁
mysql·面试·锁·行锁·死锁·间隙锁
小满zs5 小时前
Go语言第二十一章(Gin上传文件)
后端·go
个 人 练 习 生5 小时前
C++:从零基础到深入了解vector的使用
开发语言·c++·经验分享·学习·程序人生·stl
ShineWinsu6 小时前
对于Qt窗口:QMainWindow、QMenuBar、Qmenu、QAction的解析
c++·qt·菜单·qmainwindow·qaction·qmenu·qmenubar
兴趣互联6 小时前
jeecgboot nacos2.3.2 使用pgsql
java
H.莓飛6 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
hudd6686 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
Rabitebla7 小时前
【Linux操作系统】 文件篇(一):文件描述符与 Linux 文件管理机制
linux·网络·c++·笔记·学习
Flynn Liang7 小时前
HikariCP 连接池不是越大越好:I/O 密集型 Java 服务的数据库容量工程
java·数据库·mysql·高并发·连接池·hikaricp·sql 优化
学长毕设7 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端