Count Complete Tree Nodes - Teeeeeebag/LeetCode GitHub Wiki
- When talking about complete trees, this is the method that should try
Basically find the depth of left and right subtree
public class Solution {
//private
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
int l = 0, r = 0;
TreeNode crt = root;
while (crt!=null){
++l;
crt = crt.left;
}
crt =root;
while (crt!=null){
++r;
crt = crt.right;
}
if (l == r){
return (2<<(l-1))-1;
} else {
return countNodes(root.left) + countNodes(root.right)+1;
}
}
}