145. 二叉树的后序遍历 - 中等

145. 二叉树的后序遍历
二叉树的后序遍历 左 右 根
当根节点的左右子树均为空的时候 add root.val
递归解法
- 时间复杂度
O(n) n 是二叉树的节点数。每一个节点恰好被遍历一次。 - 空间复杂度
O(n) 为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)。
1 | func postorderTraversal(_ root: TreeNode?) -> [Int] { |
真迭代解法
- 时间复杂度
O(n) n 是二叉树的节点数。每一个节点恰好被遍历一次。 - 空间复杂度
O(n) 为迭代过程中显式栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)。
1 | func postorderTraversal1(_ root: TreeNode?) -> [Int] { |
假后序解法
- 时间复杂度
O(n): O(2n) 因为 2 为常数级,所以是 O(n)。 一个 n 是所有节点的遍历,另一个是最后的反转 - 空间复杂度
O(n): O(2n) 因为 2 为常数级,所以是 O(n)。一个 n 是迭代栈的开销,一个是最后反转的开销
1 | func postorderTraversal2(_ root: TreeNode?) -> [Int] { |
- Post title:145. 二叉树的后序遍历 - 中等
- Post author:xxxixxxx
- Create time:2021-02-23 15:18:00
- Post link:https://xxxixxx.github.io/2021/02/23/2000-010-145. 二叉树的后序遍历/
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
Comments