题目描述
给定二叉树的根节点 root ,返回所有左叶子之和。
代码
class Solution {
public:int getLeftSum(TreeNode* node, int& sum) {if (node == nullptr || (node->left==nullptr &&node->right==nullptr)) return 0;if (node->left) getLeftSum(node->left, sum);if (node->right) getLeftSum(node->right, sum);//判断左边的叶子节点if (node->left != nullptr && (node->left->left == nullptr && node->left->right == nullptr))sum += node->left->val;return sum;}int sumOfLeftLeaves(TreeNode* root) {int sum = 0;return getLeftSum(root, sum);}
};
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {if (root == NULL) return 0;if (root->left == NULL && root->right== NULL) return 0;int leftValue = sumOfLeftLeaves(root->left); // 左if (root->left && !root->left->left && !root->left->right) { // 左子树就是一个左叶子的情况leftValue = root->left->val;}int rightValue = sumOfLeftLeaves(root->right); // 右int sum = leftValue + rightValue; // 中return sum;}
};
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {if (root == NULL) return 0;int leftValue = 0;if (root->left != NULL && root->left->left == NULL && root->left->right == NULL) {leftValue = root->left->val;}return leftValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);}
}