题目:https://oj.leetcode.com/problems/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.
源码:Java版本算法分析:时间复杂度O(n),空间复杂度O(logn)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null) {
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}
本文介绍了一种求解二叉树最大深度的算法。该算法通过递归方式遍历二叉树,找到从根节点到最远叶节点的最长路径上的节点数,即为最大深度。时间复杂度为O(n),空间复杂度为O(logn)。
381

被折叠的 条评论
为什么被折叠?



