222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.
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 2 ^ h nodes inclusive at the last level h.

Solution: "Binary Search"

思路:

屏幕快照 2017-09-05 下午2.41.18.png

Time Complexity: T(N) = T(N / 2) + logN (for findHeight) => (logN) ^ 2
Space Complexity: O(logN)遞歸緩存

Solution Code:

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        
        int root_lheight = getLeftHeight(root);
        int left_lheight = root_lheight == 0 ? 0 : root_lheight - 1;
        int right_lheight = getLeftHeight(root.right);
        
        int count_ltree, count_rtree;
        if(right_lheight == root_lheight - 1) {
            // case1: the left subtree is complete
            count_ltree = left_lheight == 0 ? 0 : (1 << left_lheight) - 1; // 1 << x == 2 ^ x
            count_rtree = countNodes(root.right); 
        }
        else {
            // case2: the right subtree is complete (right_lheight == lheight - 2)
            count_ltree = countNodes(root.left);
            count_rtree = right_lheight == 0 ? 0 : (1 << right_lheight) - 1;
        }
        int count = 1 + count_ltree + count_rtree;   // cur_node + lef_subtree + right_sub_tree
        return count;
    }
    
    private int getLeftHeight(TreeNode root) {
        // length of all the way by left to the end 
        return root == null ? 0 : 1 + getLeftHeight(root.left);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容