I have this below code for calculating the number of nodes in a complete binary tree* without visiting all the nodes.
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
int LH=height(root,false); // depth of leftmost leaf
int RH=height(root,true); // depth of rightmost leaf
if(LH==RH){
return (int)Math.pow(2,LH)-1;
}
else return countNodes(root.left)+countNodes(root.right)+1;
}
int height(TreeNode root,boolean lr){
if(root==null)
return 0;
if(lr==false)
return 1+height(root.left,lr);
return 1+height(root.right,lr);
}
How can I determine the time complexity here? I'm confused the nodes are visited more than once.
*Complete binary tree: all the levels of the tree are filled completely except the lowest level nodes which are filled from as left as possible