404. Sum of Left Leaves #Tree (Easy)

Problem:

Find the sum of all left leaves in a given binary tree.

Example:
  3 
 / \
9  20 
   / \ 
  15  7
There are two left leaves in the binary tree, with values 9 and 15 respectively. 
Return 24.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

Solution:

Recursive solution:

检查当前节点的左子节点是否是左子叶,如果是的话,返回左子叶的值加上对当前结点的右子节点调用递归的结果;如果不是的话,对左右子节点分别调用递归函数,返回二者之和。

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == NULL) return 0;
        if (root->left && !root->left->left && !root->left->right) 
        {   //if left child is a leaf
            return root->left->val + sumOfLeftLeaves(root->right);
        }
        else return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};
Iterative solution:
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root || (!root->left && !root->right)) return 0;
        int result = 0;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            TreeNode *t = q.front(); 
            q.pop();
            if (t->left && !t->left->left && !t->left->right) 
            {  //if left child is a leaf
               result += t->left->val;
            }
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return result;
    }
};

Memo:

读清题意,left leaves。
考虑清楚递归的分界,最小情况是什么。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容