计算层序遍历最坏复杂度:
f(n)∝2h−1f(n) \propto 2 ^ {h - 1}f(n)∝2h−1,其中h为树的高度,f(n)为辅助空间,不难知道,n=2h−1n = 2^h - 1n=2h−1,nnn为树的节点个数。因此做近似处理,f(n)∝2h,n∝2hf(n) \propto 2 ^ h, n \propto 2^hf(n)∝2h,n∝2h,因此得出最简洁的表达为f(n)∝nf(n) \propto nf(n)∝n.
reference:
https://algorithmsandme.com/level-order-traversal-of-binary-tree/
As each node of the binary tree is visited at least once, time complexity O(n) along with space complexity of O(2(l-1)) where l is the number of levels in the binary tree.
注:跟Binary tree有关的几个计算公式,根节点在第0层
若满二叉树的节点数为n,总层数为h,两者关系是n=2h−1n=2^h-1n=2h−1, 第i层节点最大数:2i−12^{i-1}2i−1.
类型 | 时间复杂度 | 空间复杂度 |
---|---|---|
层序遍历 | O(n)O(n)O(n) | O(2h−1)O(2^{h-1})O(2h−1) |
前序遍历 | O(n)O(n)O(n) | O(n)O(n)O(n) |
中序遍历 | O(n)O(n)O(n) | O(n)O(n)O(n) |
后序遍历 | O(n)O(n)O(n) | O(n)O(n)O(n) |