【题目描述】python
1.一种是递归 2.非递归则使用层序遍历,队列实现bash
【python代码】app
1.递归
class Solution:
def countNodes(self, root: TreeNode) -> int:
if root:
return 1+self.countNodes(root.left)+self.countNodes(root.right)
else:
return 0
复制代码
2.非递归
class Solution:
def countNodes(self, root: TreeNode) -> int:
l=[]
re=0
if root:
l.append(root)
while l:
first=l.pop(0)
re+=1
if first.left:
l.append(first.left)
if first.right:
l.append(first.right)
return re
复制代码
【C++代码】ui
1.递归:
class Solution {
public:
int countNodes(TreeNode* root) {
return root==NULL?0:1+countNodes(root->left)+countNodes(root->right);
}
};
复制代码
2.非递归
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL)
return 0;
queue <TreeNode*> q;
int re=0;
q.push(root);
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
re+=1;
if(t->left!=NULL){q.push(t->left);}
if(t->right!=NULL){q.push(t->right);}
}
return re;
}
};
复制代码