O(n)时间复杂度解法
class Solution {
public int countNodes(TreeNode root) {
int num=0;
if(root==null){
return num;
}
Queue<TreeNode> qu=new LinkedList<>();
qu.offer(root);
TreeNode tn;
int le;
while(!qu.isEmpty()){
le=qu.size();
while(le>0){
tn=qu.poll();
if(tn.left!=null){
qu.offer(tn.left);
}
if(tn.right!=null){
qu.offer(tn.right);
}
le--;
num++;
}
}
return num;
}
}
class Solution(object):
def countNodes(self, root):
num=0
if root is None:
return num
qu=collections.deque()
qu.append(root)
while qu:
le=len(qu)
while le>0:
tn=qu.popleft()
if tn.left:
qu.append(tn.left)
if tn.right:
qu.append(tn.right)
le-=1
num+=1
return num
以下解法来自代码随想录
class Solution {
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
return countNodes(root.left)+countNodes(root.right)+1;
}
}
//解法来自代码随想录
class Solution(object):
def countNodes(self, root):
if root is None:
return 0
return self.countNodes(root.left)+self.countNodes(root.right)+1
#以下解法来自代码随想录