(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
}
相关推荐
骄马之死1 天前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
L_09071 天前
【C++】异常
开发语言·c++
liulilittle1 天前
关于拥塞控制的几点思考
网络·c++·tcp/ip·计算机网络·信息与通信·tcp·通信
郑洁文1 天前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
螺丝钉code1 天前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
Cosolar1 天前
LlamaIndex 文档解析与分块策略深度解析
人工智能·面试·架构
QT-Neal1 天前
C++ 编码规范
c++
啦啦啦啦啦zzzz1 天前
数据结构:红黑树理论
数据结构·c++·红黑树
Yolo_TvT1 天前
C++:默认构造函数
c++
摇滚侠1 天前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea