222. Count Complete Tree Nodes

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;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容