题解 | #左叶子之和#
左叶子之和
https://www.nowcoder.com/practice/405a9033800b403ba8b7b905bab0463d
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { private: void sumOfLeftLeavesHelper(TreeNode* node, int& sum, bool isLeft) { if (!node) return; // 检查当前节点是否是左叶子节点 if (isLeft && !node->left && !node->right) { sum += node->val; } // 递归遍历左子树和右子树 sumOfLeftLeavesHelper(node->left, sum, true); // 对左子节点递归时标记为左节点 sumOfLeftLeavesHelper(node->right, sum, false); // 对右子节点递归时标记为非左节点 } public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int sumOfLeftLeaves(TreeNode* root) { // write code here int sum = 0; sumOfLeftLeavesHelper(root, sum, false); return sum; } };