这个题,肯定要首先知道什么是完全二叉树,然后看了解析有n中,比较高校的应该是二分查找结合的,目前水平有限,看得不太明白,就找了2个最基本的 好理解的
var countNodes = function (root) {
// 方法一 遍历二叉树
/* if (!root) {
return null;
}
const stack = [];
stack.push(root);
let num = 0;
while (stack.length) {
const top = stack.shift();
num++;
top.left && (stack.push(top.left));
top.right && (stack.push(top.right));
}
return num; */
// 方法二 递归
return root ? countNodes(root.left) + countNodes(root.right) + 1 : null;
};