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.
計算完全二叉樹的節點數,如果直接遍歷并計算的話會是O(n)的時間復雜度。
能不能充分利用完全二叉樹的特性呢
如果從一個根節點開始一直向左和一直向右的深度是相等的,那么意味著這個根節點下面的數是滿二叉樹,其節點數直接可以算出來。
我們從根節點開始檢查,如果不是滿二叉樹就往下遞歸,每找到一顆滿二叉樹就直接返回節點數。
var countNodes = function(root) {
//獲取二叉樹一直向左或向右的高度
var getHeight = function(root,flag) {
var count = 0;
if (flag) {
while (root.left) {
count++;
root = root.left;
}
} else {
while (root.right) {
count++;
root = root.right;
}
}
return count;
};
if (!root)
return 0;
var l = getHeight(root,true);
var r = getHeight(root,false);
if (l===r) {
//如果左右高度相等,節點數等于2^樹高-1
return (2<<l) - 1;
} else {
//如果不等就遞歸
return countNodes(root.left) + countNodes(root.right) + 1;
}
};