112. 路径总和 - 简单

112. 路径总和
递归解法
- 时间复杂度
O(n),每个节点都要访问一次 - 空间复杂度
O(H),其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(logN)。
1 | func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { |
广度优先解法
- 时间复杂度
O(n),每个节点都要访问一次 - 空间复杂度
O(N),其中 N 是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。
1 | func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { |
- Post title:112. 路径总和 - 简单
- Post author:xxxixxxx
- Create time:2021-02-23 23:55:00
- Post link:https://xxxixxx.github.io/2021/02/23/2000-012-112. 路径总和/
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
Comments