Given the root
of a complete binary tree, return the number of the nodes in the tree.
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
.
Design an algorithm that runs in less than O(n)
time complexity.
Input: root = [1,2,3,4,5,6] Output: 6
Eg: Input: root = [1,2,3,4,5,6] Output: 6
Solution:
class Solution {
public int countNodes(TreeNode node) {
if (node == null) return 0;
int leftNode = findNode(node.left);
int rightNode = findNode(node.right);
int result = leftNode + rightNode + 1;
return result;
// return findNode(root);
}
public int findNode(TreeNode node){
if (node == null) return 0;
int leftNode = findNode(node.left);
int rightNode = findNode(node.right);
int result = leftNode + rightNode + 1;
return result;
}
}
Hints:
1: Understand what is a complete binary tree.
2: Know how to return the number of nodes
3: make sure the parameter of the helper function