Leetcode:count Complete Tree Nodes

Source: Internet
Author: User

1 and 2h nodes inclusive at the last level H.

Using the brute force method, the recursive asks for a timeout O (N). If the height from a node to the left is always to the right, then the subtree rooted in that node must be perfect binary tree. The number of nodes of the perfect binary tree can be calculated using a formula 2^h-1.  If the height is unequal, the return Countnode (left) + Countnode (right) + 1 is called recursively. Complexity of O (h^2)

1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8  * }9  */Ten  Public classSolution { One      Public intcountnodes (TreeNode root) { A         if(Root = =NULL)return0; -         intLeftheight =Countleft (root.left); -         intRightheight =countright (root.right); the         if(Leftheight = = rightheight) {//Perfect binary Tree -             return(1<< (leftheight+1))-1; -         } -         Else returnCountnodes (Root.left) + countnodes (root.right) + 1; +     } -      +      Public intcountleft (TreeNode root) { A         intres = 0; at          while(Root! =NULL) { -res++; -Root =Root.left; -         } -         returnRes; -     } in      -      Public intcountright (TreeNode root) { to         intres = 0; +          while(Root! =NULL) { -res++; theRoot =Root.right; *         } $         returnRes;Panax Notoginseng     } -      the}

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