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