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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容