返回

[Leetcode]404. Sum of Left Leaves (C++)

题目描述

题目链接:404. Sum of Left Leaves

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

例子

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() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        int sum = 0;
        dfs(root, false, sum);
        return sum;
    }

private:
    void dfs(TreeNode* node, bool is_left, int& sum) {
        if (!node) return;
        if (!node->left && !node->right) sum += is_left ? node->val : 0;
        dfs(node->left, true, sum);
        dfs(node->right, false, sum);
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(k) k 为树最大深度
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy