222.完全二叉树的节点个数:
题目链接:https://leetcode.cn/problems/count-complete-tree-nodes/
var countNodes = function(root) {
//利用完全二叉树的特点
if(root === null) {
return 0;
}
let left = root.left;
let right = root.right;
let leftDepth = 0, rightDepth = 0;
while(left) {
left = left.left;
leftDepth++;
}
while(right) {
right = right.right;
rightDepth++;
}
if(leftDepth == rightDepth) {
return Math.pow(2, leftDepth+1) - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
};
解题思路:
1.首先一定要知道完全二叉树的特点是什么?依次遍历左子树和右子树看他们的深度是否一样,如果一样就利用公式直接求出二叉树的节点个数即可。
2.上述代码所用的是后序遍历。