LeetCode 第104题 二叉树的最大深度

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。说明: 叶子节点是指没有子节点的节点。示例:给定二叉树 [3,9,20,null,null,15,7],    3   / \  9  20    /  \   15   7返回它的最大深度 3 。
1 class Solution104 {
2
3   private int maxDepth = 0;
4
5   public int maxDepth(TreeNode root) {
6     return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
7   }
8
9 }

原文地址:https://www.cnblogs.com/rainbow-/p/10547035.html

时间: 2024-08-05 07:41:48

LeetCode 第104题 二叉树的最大深度的相关文章

leetcode.104 计算二叉树的最大深度

题目描述:给一个二叉树,返回该二叉树的最大深度 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tre

LeetCode 第102题 二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如:给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7返回其层次遍历结果: [ [3], [9,20], [15,7]] 1 /* 2 思路1 : 用两个链表分别代替两个层次,交替使用 3 */ 4 public List<List<Integer>> levelOrder(TreeNode root) { 5 List<List<In

LeetCode 第103题 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历.(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行). 例如:给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] 思路: 与层次遍历类似,可以直接将特定层次的结果倒置 1 class Solution103 { 2 3 public List<List<Integer>> zigzagLevelOrde

LeetCode 第107题 二叉树的层次遍历II

给定一个二叉树,返回其节点值自底向上的层次遍历. (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)例如:给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7返回其自底向上的层次遍历为:[ [15,7], [9,20], [3]] 思路: 先递归层次遍历 然后将res倒置 1 class Solution107 { 2 3 List<List<Integer>> res = new ArrayList<>(); 4

图解精选 TOP 面试题 002 | LeetCode 104. 二叉树的最大深度

该系列题目取自 LeetCode 精选 TOP 面试题列表:https://leetcode-cn.com/problemset/top/ 题目描述 原题链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数. 说明:叶子节点是指没有子节点的节点. 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20

Leetcode 104. Maximum Depth of Binary Tree(二叉树的最大深度)

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 分析:求二叉树的最大深度 解法一:很容易想到的便是递归(深度优先搜索) (1)如果根节点是空,则返回0:否则转到(2) (2)  l = 左子树的最大深度; r = 右子树的最大深

LeetCode(104):二叉树的最大深度

Easy! 题目描述: 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数. 说明: 叶子节点是指没有子节点的节点. 示例:给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回它的最大深度 3 . 解题思路: 求二叉树的最大深度问题用到深度优先搜索DFS,递归的完美应用,跟求二叉树的最小深度问题原理相同. C++解法一: 1 class Solution { 2 public: 3 int maxDepth(Tr

lintcode 容易题:Maximum Depth of Binary Tree 二叉树的最大深度

题目: 二叉树的最大深度 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的距离. 样例 给出一棵如下的二叉树: 1 / \ 2 3 / 4 5 这个二叉树的最大深度为3. 解题: 递归方式求树的深度,记住考研时候考过这一题 Java程序: /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeN

【leetcode 简单】 第七十一题 二叉树的所有路径

给定一个二叉树,返回所有从根节点到叶子节点的路径. 说明: 叶子节点是指没有子节点的节点. 示例: 输入: 1 / 2 3 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x