【发布时间】:2021-08-16 19:35:14
【问题描述】:
我目前在 leetcode 上的 94. Binary Tree Traversal 上,我不确定如何分析问题的运行时间和空间复杂度。在我看来,这个问题的时间复杂度似乎是 O(n),其中 n 是树中的节点数,因为我们需要遍历树中的每个节点。但是,对于空间来说争议更大,我认为是 O(h),其中 h 是树的最大高度,因为我认为递归引起的调用堆栈可以达到树的最大高度,并且当我们回溯时,堆栈将弹出。有人认为它实际上是 O(n),因为在树完全左偏或右偏的最坏情况下,调用堆栈与可用节点的数量一样深,但不是 O(h) 也适用于此因为最大高度也是树中节点的数量。虽然 O(n) 是最坏的情况,但 O(h) 似乎更准确,更适合包括上面的示例在内的更多场景,答案应该是哪一个?或者更具体地说,在编码面试中面试官会接受哪一个?
我还将在此处粘贴我的解决方案:
class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
helper(root, res);
return res;
}
public void helper(TreeNode root, List < Integer > res) {
if (root != null) {
if (root.left != null) {
helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
}
}
【问题讨论】:
标签: algorithm complexity-theory space-complexity code-complexity