[Leetcode] [JavaScript] Count Complete Tree Nodes

Source: Internet
Author: User

Count Complete Tree Nodes

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

https://leetcode.com/problems/count-complete-tree-nodes/

Tricky approach, to the left to find the deepest leaf node, to the right to find the deepest leaf node.

If their depth is the same, the description is a complete binary tree, the node points are applied to the formula 2^n-1.

Otherwise, the same method is used to recursively Saozi the right sub-tree of this point.

2 of the cyclic conditions are written as while (Leftchild && leftchild.val), Val may be 0, the result is not orz.

1 /**2 * Definition for a binary tree node.3 * Function TreeNode (val) {4 * This.val = val;5 * This.left = This.right = null;6  * }7  */8 /**9 * @param {TreeNode} rootTen * @return {number} One  */ A varCountnodes =function(root) { -     returnTreeNodes (root); -  the     functiontreenodes (node) { -         if(!node) { -             return0; -}Else{ +             varleftdepth = 0; -             varrightdepth = 0; +             varLeftchild =Node.left; A              while(leftchild) { atleftdepth++; -Leftchild =Leftchild.left; -             } -             varRightchild =Node.right; -              while(rightchild) { -rightdepth++; inRightchild =Rightchild.right; -             } to             if(Leftdepth = = =rightdepth) { +                 returnMath.pow (2, leftdepth + 1)-1; -}Else{ the                 returnTreeNodes (Node.left) + treenodes (node.right) + 1; *             } $         }Panax Notoginseng     } -};

[Leetcode] [JavaScript] Count Complete Tree Nodes

Related Article

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.