【題目描述】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;
}
};
複製代碼