[LeetCode][JavaScript]Count Complete Tree Nodes

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, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

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


Tricky的做法,往左找到最深的叶子节点,往右再找最深的叶子节点。

如果他们的深度一样,说明是棵完全二叉树,节点数套用公式2^n - 1。

否则再用同样的方法递归这个点的左子树和右子树。

犯2把循环条件写成了while(leftChild && leftChild.val),val可能是0,结果就不对了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} root
10  * @return {number}
11  */
12 var countNodes = function(root) {
13     return treeNodes(root);
14 
15     function treeNodes(node){
16         if(!node){
17             return 0;
18         }else{
19             var leftDepth = 0;
20             var rightDepth = 0;
21             var leftChild = node.left;
22             while(leftChild){
23                 leftDepth++;
24                 leftChild = leftChild.left;
25             }
26             var rightChild = node.right;
27             while(rightChild){
28                 rightDepth++;
29                 rightChild = rightChild.right;
30             }
31             if(leftDepth === rightDepth){
32                 return Math.pow(2, leftDepth + 1) - 1;
33             }else{
34                 return treeNodes(node.left) + treeNodes(node.right) + 1;
35             }
36         }
37     }
38 };
原文地址:https://www.cnblogs.com/Liok3187/p/4558221.html