144. 二叉树的前序遍历 - 中等

144. 二叉树的前序遍历
二叉树的前序遍历 根 左 右
当根节点不为空时,直接把 root.val add list
递归解法
- 时间复杂度
O(n) n 是二叉树的节点数。每一个节点恰好被遍历一次。 - 空间复杂度
O(n) 为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)。
1 | func preorderTraversal(_ root: TreeNode?) -> [Int] { |
迭代解法
- 时间复杂度
O(n) n 是二叉树的节点数。每一个节点恰好被遍历一次。 - 空间复杂度
O(n) 为迭代过程中显式栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n)。
1 | func preorderTraversal(_ root: TreeNode?) -> [Int] { |
- Post title:144. 二叉树的前序遍历 - 中等
- Post author:xxxixxxx
- Create time:2021-02-23 13:09:00
- Post link:https://xxxixxx.github.io/2021/02/23/2000-009-144. 二叉树的前序遍历/
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
Comments