class Solution {
public:
void traversal(TreeNode* root, int& sum) {
if (root == nullptr) return;
traversal(root->left, sum);
if (root->left == nullptr && root->right == nullptr) {
sum += root->val;
return;
}
else if (root->right == nullptr)
return;
else if (root->right->left == nullptr && root->right->right == nullptr)
return;
else traversal(root->right, sum);
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
//对单节点的情况进行特殊处理
if (root->left == nullptr && root->right == nullptr) return 0;
traversal(root, sum);
return sum;
}
};
LeetCode404.左叶子之和
最新推荐文章于 2024-08-10 15:25:17 发布