404. 左叶子之和

当当前结点的左节点不为空,左节点的左节点和右节点为空,说明是叶子结点

一、递归

  1. class Solution {
  2. public:
  3. int sumOfLeftLeaves(TreeNode* root) {
  4. //终止条件
  5. if(root==NULL)return 0;
  6. //单层递归
  7. int leftnums = sumOfLeftLeaves(root->left);//左
  8. int rightnums = sumOfLeftLeaves(root->right);//右
  9. //中
  10. int midnums = 0;
  11. if(root->left && !root->left->left && !root->left->right)
  12. midnums+=root->left->val;
  13. return leftnums+rightnums+midnums;
  14. }
  15. };

二、迭代

  1. class Solution {
  2. public:
  3. int sumOfLeftLeaves(TreeNode* root) {
  4. if(root==NULL)return 0;
  5. stack<TreeNode*> st;
  6. int sum=0;
  7. st.push(root);
  8. while(!st.empty())
  9. {
  10. TreeNode* cur = st.top();
  11. st.pop();
  12. if(cur->left&& !cur->left->left && !cur->left->right)
  13. sum+=cur->left->val;
  14. if(cur->left)st.push(cur->left);
  15. if(cur->right)st.push(cur->right);
  16. }
  17. return sum;
  18. }
  19. };