[LeetCode] Sum of Left Leaves 左子叶之和

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.

这道题让我们求一棵二叉树的所有左子叶的和,那么看到这道题我们知道这肯定是考二叉树的遍历问题,那么最简洁的写法肯定是用递归,由于我们只需要累加左子叶之和,那么我们在进入递归函数的时候需要知道当前结点是否是左子节点,如果是左子节点,而且该左子节点再没有子节点了说明其是左子叶,那么我们将其值加入结果res中,我们用一个bool型的变量,如果为true说明当前结点是左子节点,若为false则说明是右子节点,不做特殊处理,整个来说就是个递归的先序遍历的写法,参见代码如下:

解法一:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root || (!root->left && !root->right)) return 0;
        int res = 0;
        helper(root->left, true, res);
        helper(root->right, false, res);
        return res;
    }
    void helper(TreeNode* node, bool left, int& res) {
        if (!node) return;
        if (!node->left && !node->right && left) res += node->val;
        helper(node->left, true, res);
        helper(node->right, false, res);
    }
};

我们还可以写的更简洁一些,不需要写其他的函数,直接在原函数中检查当前节点的左子节点是否是左子叶,如果是的话,则返回左子叶的值加上对当前结点的右子节点调用递归的结果;如果不是的话,我们对左右子节点分别调用递归函数,返回二者之和,参见代码如下:

解法二:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root) return 0;
        if (root->left && !root->left->left && !root->left->right) {
            return root->left->val + sumOfLeftLeaves(root->right);
        }
        return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

我们也可以使用迭代来解,因为这道题的本质是遍历二叉树,所以我们可以用层序遍历的迭代写法,利用queue来辅助,注意对左子叶的判断和处理,参见代码如下:

解法三:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root || (!root->left && !root->right)) return 0;
        int res = 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) res += t->left->val;
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return res;
    }
};

我们也可以用stack来辅助,对比上面的解法,我们发现几乎一模一样,只是把queue换成了stack,但实际上遍历的顺序不同,这种方法是先序遍历的迭代写法,参见代码如下:

解法四:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (!root || (!root->left && !root->right)) return 0;
        int res = 0;
        stack<TreeNode*> s;
        s.push(root);
        while (!s.empty()) {
            TreeNode *t = s.top(); s.pop();
            if (t->left && !t->left->left && !t->left->right) res += t->left->val;
            if (t->left) s.push(t->left);
            if (t->right) s.push(t->right);
        }
        return res;
    }
};

参考资料:

https://discuss.leetcode.com/topic/60467/3-line-c-solution

https://discuss.leetcode.com/topic/60381/java-solution-using-bfs

https://discuss.leetcode.com/topic/60415/java-solution-with-stack

LeetCode All in One 题目讲解汇总(持续更新中...)

时间: 2024-10-16 13:32:34

[LeetCode] Sum of Left Leaves 左子叶之和的相关文章

404 Sum of Left Leaves 左叶子之和

计算给定二叉树的所有左叶子之和.示例:    3   / \  9  20    /  \   15   7在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24. 详见:https://leetcode.com/problems/sum-of-left-leaves/description/ C++: 方法一: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *le

LeetCode 404. Sum of Left Leaves (左子叶之和)

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. 题目标签:Tree 这道题目给了我们一个二叉树,让我们找到所有左子叶之和.这里需要另外一个function - sumLeftLeaves 还要一个int

[LeetCode] Sum of Left Leaves

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. 题目要求树的所有左叶节点的和,根据题意判断出所有左叶节点,使用递归即可. class Solution { public: int sumOfLeftLe

[LeetCode] Sum of Two Integers 两数之和

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases. 这道题是CareerCup上的一道原题,难道

[LeetCode] Sum of Square Numbers 平方数之和

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False s

[Swift]LeetCode404. 左叶子之和 | Sum of Left Leaves

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. 计算给定二叉树的所有左叶子之和. 示例: 3 / 9 20 / 15 7 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24 1 /**

【leetcode 简单】 第九十四题 左叶子之和

计算给定二叉树的所有左叶子之和. 示例: 3 / 9 20 / 15 7 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumOfLeft

404. Sum of Left Leaves (Easy)

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. 题意:计算所有左叶子的和思路:遍历二叉树 1.检查当前节点的左子节点是否是左子叶:2.若是叶子节点,则返回左子叶的值加上对当前结点的右子节点调用递归的结果

leetcode-404. Sum of Left Leaves

404. Sum of Left Leaves 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.求所有的左叶子节点的和java代码: /** * Definition for a binary tree