*count Complete Tree Nodes

Source: Internet
Author: User

Topic:

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, was completely filled, and all nodes As far left as possible. It can has between 1 and 2hnodes inclusive at the last level H.

Ideas:

Full v.s. Complete Binary Trees

According to Wikipedia

    • A full binary tree (sometimes proper binary tree or 2-tree) are a tree in which every node other than the leaves have both ch Ildren.
    • A complete binary tree was a binary tree in which every level, except possibly the last, was completely filled, and all node S is as far as possible.

Steps to solve this problem:
1) Get the height of Left-most part
2) Get the height of Right-most part
3) When they is equal, the # of nodes = 2^h-1
4) when they is not equal, recursively get # of nodes from Left&right sub-trees

Time complexity is O (h^2).

Code:

1  Public intcountnodes (TreeNode root) {2     if(root==NULL)3         return0;4  5     intleft = Getleftheight (root) +1; 6     intright = Getrightheight (root) +1;7  8     if(left==Right ) {9         return(2<< (Left-1))-1;Ten}Else{ One         returnCountnodes (Root.left) +countnodes (root.right) +1; A     } - } -   the  Public intGetleftheight (TreeNode N) { -     if(n==NULL)return0; -   -     intHeight=0; +      while(n.left!=NULL){ -height++; +n =N.left; A     } at     returnheight; - } -   -  Public intGetrightheight (TreeNode N) { -     if(n==NULL)return0; -   in     intHeight=0; -      while(n.right!=NULL){ toheight++; +n =N.right; -     } the     returnheight; *}

reference:http://www.programcreek.com/2014/06/leetcode-count-complete-tree-nodes-java/

*count Complete Tree Nodes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.