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 2hnodes inclusive at the last level h.

解题方法

分左右子樹去計算高度

   public int countNodes(TreeNode root){
        //corner case
        if(root == null){ return 0;}

        // divide and conquer
        int L = countLeft(root.left);
        int R = countLeft(root.right);
        if(L == R){
            return countNodes(root.right) + (1 << L);
        }else{
            return countNodes(root.left) + (1 << R);
        }
    }

    private int countLeft(TreeNode root){
        int h = 0;
        while(root != null){
            h++;
            root = root.left;
        }
        return h;
    }

results matching ""

    No results matching ""