[Leetcode] 222 Count complete Tree Nodes

Source: Internet
Author: User

1. The easiest way to think: recursively traverse each point, calculate the total number of points, time complexity O (n), unfortunately, timed out. (It's not too good to be justified. = =)

Class Solution {public:    int countnodes (treenode* root) {        if (root==null)        return 0;        int res=0;        if (root->left)        res+=countnodes (root->left);        if (root->right)        res+=countnodes (root->right);                return res+1;}    ;
2. We should make full use of the nature of the full binary tree, originally wanted to use the law, so that only the last layer of the knot points can be, but not the implementation. So we put the problem to the overall situation, under what circumstances can use the full binary tree of the nature of the use of geometric series and directly to find it? Obviously, when the height of the subtree is equal. Therefore, we also found the condition of recursive termination, problem solving, complexity O (logn).

Class Solution {public:    int countnodes (treenode* root) {       if (root==null)       return 0;       int lno=0,rno=0;       TreeNode *l=root,*r=root;       while (L->left)       {         lno++;         l=l->left;       }       while (R->right)       {         rno++;         r=r->right;       }       if (Lno==rno)       return pow (2.0,lno+1)-1;              Return 1+countnodes (Root->left) +countnodes (root->right);    };


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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