# [Leetcode] Count Complete Tree Nodes

Source: Internet
Author: User

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.

Thinking of solving problems

A full traversal will time out. The height of the right subtree of Saozi can be calculated from the root node, respectively. If the assumption is equal, then the tree is full two, and the number of nodes is 2 n ? 1 。 Assuming the height is unequal, the number of nodes is left dial hand tree node number + Right sub-tree node number +1. (height n is the height that includes the root node)

Implementation code
``//runtime:100 MS/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */Class Solution { Public:int Countnodes(treenode* Root) {intLefthight = GetLeft (root);intRightheight = GetRight (root);if(Lefthight = = rightheight) {returnPow2, Lefthight)-1; }return 1+ countnodes (root->left) + countnodes (root->right); }Private:int GetLeft(TreeNode *root) {intHeight =0; while(Root)            {height++;        root = root->left; }returnHeight }intGetRight (TreeNode *root) {intHeight =0; while(Root)            {height++;        root = root->right; }returnHeight }};``

[Leetcode] Count Complete Tree Nodes

Related Keywords:

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.