LeetCode刷题实战222:完全二叉树的节点个数
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
示例
解题
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(!root){
return 0
}
return 1 + countNodes(root.left) + countNodes(root.right)
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(!root){
return 0
}
let queue = [root]
let res = 1
while(queue.length){
let node = queue.shift()
if(node.left){
queue.push(node.left)
res++
}
if(node.right){
queue.push(node.right)
res++
}
}
return res
};
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(!root){
return 0
}
let leftHeight = 0, rightHeight = 0
let leftNode = root, rightNode = root
while(leftNode){
leftHeight++
leftNode = leftNode.left
}
while(rightNode){
rightHeight++
rightNode = rightNode.right
}
if(leftHeight === rightHeight){
return 2 ** leftHeight - 1
}
return 1 + countNodes(root.left) + countNodes(root.right)
};