222 Count Complete Tree Nodes

Source: Internet
Author: User

1, this problem will time out if it is purely recursive and does not use it as a complete binary tree.

2. In order to use this condition, compare the height of the left and right two sub-numbers: 1, if the left subtree is a complete binary tree 2, if not equal, then it is a complete binary tree.

3, the total binary tree node number is POW (2,depth)-1, so you can save time without recursion points.

4, because it is the complete binary tree, the depth of the subtree can only be obtained by searching the left son.

Overall complexity O (LGN * lgn)

classSolution:#@param {TreeNode} root    #@return {integer}    defCountnodes (self, root):if  notRoot:return0 leftdepth=self.getdepth (root.left) rightdepth=self.getdepth (root.right)ifLeftdepth = =rightdepth:returnPow (2, leftdepth) +self.countnodes (root.right)Else:            returnPow (2, rightdepth) +self.countnodes (root.left)defgetdepth (self, root):if  notRoot:return0return1 + self.getdepth (root.left)

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.