题目
思路
叶子结点且是左叶子结点,累加
易错点
需要注意根结点为空的情况
if(root==NULL)return 0; //易错点
题解
dfs
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeafNode(TreeNode* root){
return !root->left&&!root->right;
}
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL)return 0;
int sum=0;
if(root->left!=NULL)
sum+=isLeafNode(root->left)?root->left->val:sumOfLeftLeaves(root->left);
if(root->right!=NULL)
sum+=isLeafNode(root->right)?0:sumOfLeftLeaves(root->right);
return sum;
}
int main() {
TreeNode * root = new TreeNode(3);
TreeNode * rootl = new TreeNode(9);
TreeNode * rootr = new TreeNode(20);
TreeNode * rootrl = new TreeNode(15);
TreeNode * rootrr = new TreeNode(7);
rootr->left=rootrl;
rootr->right=rootrr;
root->left = rootl;
root->right = rootr;
int sum = sumOfLeftLeaves(root);
cout<<sum;
return 0;
}
bfs
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeafNode(TreeNode* root) {
return !root->left&&!root->right;
}
int sumOfLeftLeaves(TreeNode* root) {
if(root==NULL)return 0; //易错点
queue<TreeNode *> q;
q.push(root);
int sum =0;
while(!q.empty()) {
TreeNode * now = q.front();
q.pop();
if(now->left) {
if(isLeafNode(now->left)) {
sum+=now->left->val;
}else{
q.push(now->left);
}
}
if(now->right&&!isLeafNode(now->right)) {
q.push(now->right);
}
}
return sum;
}
int main() {
TreeNode * root = new TreeNode(3);
TreeNode * rootl = new TreeNode(9);
TreeNode * rootr = new TreeNode(20);
TreeNode * rootrl = new TreeNode(15);
TreeNode * rootrr = new TreeNode(7);
rootr->left=rootrl;
rootr->right=rootrr;
root->left = rootl;
root->right = rootr;
int sum = sumOfLeftLeaves(root);
cout<<sum;
return 0;
}