DFS
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
O(n)的遍历方法,没有用到完全二叉树的性质
DFS变种
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
if(left == right){
return (1 << left) + countNodes(root.right);
}else{
return (1 << right) + countNodes(root.left);
}
}
public int getDepth(TreeNode node){
int depth = 0;
while(node != null) {
depth++;
node = node.left;
}
return depth;
}
}
如果左右深度相同,则计算右子树节点数,如果左边比右边大,即不是满二叉树了,则计算左子树个数