题目:
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
题解:
可以利用完全二叉树的性质,当往左边递归时,总会遇到满二叉树,此时就根据满二叉树的性质来计算二叉树的结点个数, 满二叉树结点个数 = dep ** 2 - 1
var countNodes = function(root) {
if(!root) return 0
let left = root.left
let right = root.right
let leftDep = 0
let rightDep = 0
while(left){
left = left.left
leftDep++
}
while(right){
right = right.right
rightDep++
}
if(leftDep === rightDep){
return Math.pow(2, leftDep + 1) - 1
}
return countNodes(root.left) + countNodes(root.right) + 1
};