# leetcode 404. 左叶子之和-递归算法与迭代算法

```    3
/ \
9  20
/  \
15   7

``````    int sumOfLeftLeaves(TreeNode* root) {
//如果是空节点
if(root==NULL) return 0;
//如果它的左孩子恰好是左叶子
if((root->left!=NULL) && (root->left->left==NULL)&&(root->left->right==NULL))
return root->left->val+sumOfLeftLeaves(root->right);
//左孩子不是左叶子的情况
return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}``````

``````    int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL) return 0;
if((root->left||root->right)==NULL) return 0;
if((root->left!=NULL) && (root->left->left==NULL)&&(root->left->right==NULL))
return root->left->val+sumOfLeftLeaves(root->right);
return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}``````

``````int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL) return 0;
int ans=0;
stack<TreeNode*> s;
s.push(root);
while(s.size())
{
root=s.top();
s.pop();
if(root==NULL)
continue;
if((root->left || root->right)==NULL)
continue;
while(root->left)
{
s.push(root->right);
root=root->left;
}
//找到一个左叶子
if(root->right==NULL)
ans+=root->val;
else
s.push(root->right);
}
return ans;
}``````

;