404. 左叶子之和
当当前结点的左节点不为空,左节点的左节点和右节点为空,说明是叶子结点
一、递归
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
//终止条件
if(root==NULL)return 0;
//单层递归
int leftnums = sumOfLeftLeaves(root->left);//左
int rightnums = sumOfLeftLeaves(root->right);//右
//中
int midnums = 0;
if(root->left && !root->left->left && !root->left->right)
midnums+=root->left->val;
return leftnums+rightnums+midnums;
}
};
二、迭代
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL)return 0;
stack<TreeNode*> st;
int sum=0;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
if(cur->left&& !cur->left->left && !cur->left->right)
sum+=cur->left->val;
if(cur->left)st.push(cur->left);
if(cur->right)st.push(cur->right);
}
return sum;
}
};