//迭代法
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*>st;
if(root == nullptr) return 0;
st.push(root);
int result = 0;
while(!st.empty()){
TreeNode* node = st.top();
st.pop();
if(node->left!=nullptr && node->left->left==nullptr && node->left->right==nullptr){
result += node->left->val;
}
if(node->left) st.push(node->left);
if(node->right) st.push(node->right);
}
return result;
}
};
//递归法
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == nullptr) return 0;
int left = sumOfLeftLeaves(root->left);
if(root->left && !root->left->left && !root->left->right){
left = root->left->val;
}
int right = sumOfLeftLeaves(root->right);
int sum = left + right;
return sum;
}
};
222.完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == nullptr) return 0;
return 1+countNodes(root->left)+countNodes(root->right);
}
};
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*>que;
int result = 0;
if(root != nullptr) que.push(root);
while(!que.empty()){
int size = que.size();
for(int i=0;i<size;i++){
TreeNode* node = que.front();
que.pop();
result++;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return result;
}
};