222 Count Complete Tree Nodes
Last updated
Last updated
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
这题如果用bfs直接数O(n)会超时,所以只能向logn靠拢。因为这个是满二叉树,所以我们用了logn去数高度,然后再logn去数右子树。T:O(logn ^ 2). 这一题3年想了3次,感觉不太能记住推导过程,只能记住结论了。这里的结论是,每一次循环,都是把除了现在这个点以外的另一边的点全加进去。这个数就是2的h或2的h - 1次方个点。