Count Complete Tree Nodes
Last updated
Was this helpful?
Last updated
Was this helpful?
Given acompletebinary tree, count the number of nodes.
Definition of a complete binary tree from: 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 2hnodes inclusive at the last level h.
Solution:
a这道题的解题关键就是,总是把左右子树分开计算高度,如果高度相同,可以说明左子树是满二叉树,如果高度不同,则可以排右子树,有点类似于二分查找的精髓,节点个数根层级的关系就是,pow(2, h) - 1 , 在每次排除的时候没有计算根节点,需要把根节点也加进去。