Binary search application (2)

1. The number of complete binary tree nodes

1. Question: Given the root node of a complete binary tree, return the number of nodes in the binary tree.

2. Steps:

  1. Calculate the height of the left subtree and the right subtree, denoted as h1, h2

  2. If h1=h2, the left subtree must be full, n+=2^h1-1. Calculate the right subtree

  3. If h1>h2, then the right subtree is full, n+=2^h2-1, calculate the left subtree

  4. If h1=0, end.

3. Implement the code

int count1(TreeNode* root){
    int n=0;
    n++;
    int h1=0;int h2=0;
    TreeNode* current=root->left;
    while(current!=NULL) {
        h1 ++ ;
        current=current->left;
    }
    current=root->right;
    while(current!=NULL) {
        h2++;
        current=current->left;
    }

    if (h1== 0 ) return n; // no left and right subtrees

    if (h1==h2){ // The left subtree is full, count the right subtree 
        n+=pow( 2 ,h1)- 1 ;
        n+=count1(root->right);
    } else { // The right subtree is full, count the left subtree 
        n+=pow( 2 ,h2)- 1 ;
        n+=count1(root->left);
    }
    return n;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325149764&siteId=291194637