8.8 Leetcode 222 Count complete Tree Nodes

Source: Internet
Author: User

Question:

Count Complete Tree NodesTotal accepted:11040 Total submissions:53992my submissions QuestionSolution

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

Analysis:

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

 Public intCountnodes (TreeNode root) {//Notice The traditional traversal would exceed the time limit and we also can ' t use Math.pow () cause it is too slow.        if(Root = =NULL)return0; TreeNode LN= root, RN =Root; intL = 0, r = 0;  while(LN! =NULL) {L++; ln=Ln.left; }         while(rn! =NULL) {R++; RN=Rn.right; }//Math.pow (2,n) = 2<< (n-1) e.g. 2^1 = = 2 = 2<<0        if(L = = r)return(2<< (L-1))-1;//notice "<<" is right connect so we need "() out of 2<< (L-1)"        return1 + countnodes (root.left) +countnodes (root.right); }  

8.8 Leetcode 222 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.