Count Complete Tree Nodes
Question
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.
Anaylsis
普通的依次遍历每个节点返回总个数会TLE
由于题目要求查的是完全二叉树的节点个数,而完全二叉树只有最底层的叶子节点可以为空,存在的叶子节点都在最下层的左侧,利用该性质可以尽快得出总节点个数。
设一完全二叉树节点root的高度为h,判断右子树高度=h-1是否成立
- 成立。root的左子树为一棵高度为h-1的完全二叉树。节点个数count=2^(h-1)+右子树节点个数
- 不成立。root的右子树为一棵高度为h-2的完全二叉树。节点个数count=2^(h-2)+左子树节点个数
为了方便计算,height函数返回的树高度为1~n-1
I have O(log(n)) steps. Finding a height costs O(log(n)). So overall O(log(n)^2).
Code
|
|
|
|