(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
}
相关推荐
我今晚不熬夜8 分钟前
使用单调栈解决力扣第42题--接雨水
java·数据结构·算法·leetcode
珍珠是蚌的眼泪12 分钟前
LeetCode_哈希表
leetcode·哈希表·快乐数·字母异位词
拾光拾趣录24 分钟前
基础 | 🔥6种声明方式全解⚠️
前端·面试
flashlight_hi1 小时前
LeetCode 分类刷题:209. 长度最小的子数组
javascript·算法·leetcode
源代码•宸1 小时前
C++高频知识点(十八)
开发语言·c++·经验分享·多线程·互斥锁·三次握手·字节对齐
mit6.8241 小时前
修复C++14兼容性问题& 逻辑检查
开发语言·c++
御承扬2 小时前
HarmonyOS NEXT系列之编译三方C/C++库
c语言·c++·harmonyos
louisgeek2 小时前
Java UnmodifiableList 和 AbstractImmutableList 的区别
java
许怀楠2 小时前
【C++】类和对象(下)
c++
danzongd2 小时前
浅谈C++ const
c++·内存·优化·汇编语言·计算机系统·寄存器