前言
题目: 404. 左叶子之和
文档: 代码随想录------左叶子之和
编程语言: C++
解题状态: 成功解答!
思路
注意左叶子节点的定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点。
代码
cpp
/**
* 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:
void sumLeft(TreeNode* node, int& sum) {
if (node == NULL) return;
TreeNode* leftNode = node -> left;
TreeNode* rightNode = node -> right;
if (leftNode) {
if (leftNode -> left == NULL && leftNode -> right == NULL) {
sum += leftNode -> val;
} else {
sumLeft(leftNode, sum);
}
}
if (rightNode) {
sumLeft(rightNode, sum);
}
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
sumLeft(root, sum);
return sum;
}
};