[LeetCode 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.

递归查找左右子树的nodes number, 注意base case.并利用complete tree 性质


public int countNodes(TreeNode root) {
        if(root == null) return 0;
        TreeNode n1 = root.left;
        int leftHeight = 1;
        while(n1!=null){
            leftHeight++;
            n1 = n1.left;
        }
        n1 = root.right;
        int rightHeight = 1;
        while(n1!=null){
            rightHeight++;
            n1 = n1.right;
        }
        if(leftHeight == rightHeight){
            return (1<<leftHeight) -1;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }


你可能感兴趣的:(LeetCode,tree)