[Leetcode-java] 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.

Test instructions: Find the number of nodes for a fully binary tree.

Idea: To find the last layer of the last node, you can judge the left and right nodes the most of the number of layers is the same, if the same, then the left subtree is full of two fork tree, if different, the tree is full two.

In the process of solving, it is necessary to use the power of the operation, if the use of Math.pow will time out, you can consider a bit operation, but to consider 2 of the 0 power of the special case.

Code:

 Public classSolution { Public intcountnodes (TreeNode root) {if(Root = =NULL)            return0; intleft =Countlevel (Root.left); intright =Countlevel (root.right); intLeftpow = 2<< (left-1); intRightpow = 2<< (right-1); if(left = = 0)//0 Power,<< not come outLeftpow = 1; if(right = = 0) Rightpow= 1; if(left = =Right ) {            returnLeftpow +countnodes (root.right); }Else            returnRightpow +countnodes (Root.left); }         Public intcountlevel (TreeNode root) {if(Root = =NULL)            return0; intCount = 0;  while(Root! =NULL) {Count++; Root=Root.left; }                returncount; }}

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