“递归方法(Java)的时间复杂度是多少?”;二叉树的最大深度;?

“递归方法(Java)的时间复杂度是多少?”;二叉树的最大深度;?,java,recursion,time-complexity,Java,Recursion,Time Complexity,这个问题取自LeetCode的“二叉树的最大深度”: 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. 递归方法非常简单: public int maxDepth (TreeNode root) { if(root

这个问题取自LeetCode的“二叉树的最大深度”:

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.
递归方法非常简单:

public int maxDepth (TreeNode root) {  
    if(root == null)  
        return 0;  
    return Math.max(maxDepth(root.left),maxDepth(root.right))+1;  
}  

我就是想不出这个解决方案的时间复杂性。有人说这是
O(n)
。是不是同时计算了
maxDepth(root.left)
maxDepth(root.right)
,这会使时间复杂度
O(lg(n))

根据Java规范,函数的最左边的参数首先完全计算,然后是右边的参数。它们不是按算法同时计算的,也不是按时间顺序在不同的线程/内核上同时执行的

可以这样想:算法将精确地遍历每个节点一次。这意味着算法是
O(n)


如果您不确信,您可以使用(此处为Wikipedia的注释)以不太全面的方式得出相同的结论:

对于大小为N的树,我们执行两个调用,每个调用在树的一半上,加上我们对该节点的常量工作(检查null并添加1):

该定理有多种情况,并表示情况1涵盖了
f(n)
O(n^c)
的算法,其中
c
,如上所述。我们的
f(n)
O(n^0)
(常数)和
logb(a)=log2(2)=1
。然后,该定理说明运行时是:

T(n) = Θ(n^log_b(a))
这对我们来说意味着

T(n) = Θ(n^1) = Θ(n)
这是达成相同答案的一般化但长期的方法

maxDepth(root.left)和maxDepth(root.right)只能在并行运行时同时计算,如果并行运行,复杂性取决于可并行运行的可用处理器数量。也就是说,您的Java代码没有并行运行,因为所有代码都在同一个线程上运行

假设按顺序执行,
maxDepth
必须遍历整个树,因为它不知道某个路径是否会导致最大深度,直到它到达该路径的末端。因此,时间复杂度为O(n)

T(n) = Θ(n^1) = Θ(n)