Redian新闻
>
print bst in level order dfs为什么是O(N)不应该是O(N^2)吗?
avatar
print bst in level order dfs为什么是O(N)不应该是O(N^2)吗?# JobHunting - 待字闺中
w*j
1
http://discuss.leetcode.com/questions/49/binary-tree-level-orde
Complexity Analysis:
Although the DFS solution traverse the same node multiple times, it is not
another order slower than the BFS solution. Here is the proof that the DFS
solution above runs in O(N) time, where N is the number of nodes in the
binary tree and we assume that the binary tree is balanced.
We first compute the complexity of printLevel for the kth level:
T(k) = 2T(k-1) + c
= 2k-1 T(1) + c
= 2k-1 + c
Assuming it's a balanced binary tree, then it would have a total of lg N
levels.
Therefore, the complexity of printing all levels is:
T(1) + T(2) + ... + T(lg N)
= 1 + 2 + 22 + ... + 2lg N-1 + c
= O(N)
T(k)那个倒是明白,但是traverse kth level的时候不是1 - k-1都要再来一遍吗?
这样的话,就喝底下哪个公式不符了吧....
avatar
w*j
2
没人知道吗....?
avatar
r*e
3
T(k)本身就是travese 1到k层的cost,不是单单访问第k层的

【在 w******j 的大作中提到】
: http://discuss.leetcode.com/questions/49/binary-tree-level-orde
: Complexity Analysis:
: Although the DFS solution traverse the same node multiple times, it is not
: another order slower than the BFS solution. Here is the proof that the DFS
: solution above runs in O(N) time, where N is the number of nodes in the
: binary tree and we assume that the binary tree is balanced.
: We first compute the complexity of printLevel for the kth level:
: T(k) = 2T(k-1) + c
: = 2k-1 T(1) + c
: = 2k-1 + c

avatar
w*j
4

可是,上面说
T(1) = 1, T(2) = 2, T(3) = 2^2.....
但是我怎么觉得T(2)就是1 + 2 = 3,
T(3) = T(2) + 4 = 7?
我哪里想错了吗?

【在 r*******e 的大作中提到】
: T(k)本身就是travese 1到k层的cost,不是单单访问第k层的
avatar
r*e
5
T(1) = 1
T(2) = 2*T(1) + c
T(3) = 2*T(2) + c
没看懂你的T(3) = T(2) + 4 是怎么来的

【在 w******j 的大作中提到】
:
: 可是,上面说
: T(1) = 1, T(2) = 2, T(3) = 2^2.....
: 但是我怎么觉得T(2)就是1 + 2 = 3,
: T(3) = T(2) + 4 = 7?
: 我哪里想错了吗?

avatar
w*j
6

好像有点明白了....汗....谢谢你!

【在 r*******e 的大作中提到】
: T(1) = 1
: T(2) = 2*T(1) + c
: T(3) = 2*T(2) + c
: 没看懂你的T(3) = T(2) + 4 是怎么来的

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。