题目链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
题目如下:
递归:
/**
* 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:
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
dfs(root,sum);
return sum;
}
void dfs(TreeNode* root,int& sum){
if(root==NULL) return ;
//存在左叶子节点:如果当前左节点不为空,且左节点没有左右孩子节点
if(root->left&&root->left->left==NULL&&root->left->right==NULL){
sum+=root->left->val;
}
if(root->left) dfs(root->left,sum);
if(root->right) dfs(root->right,sum);
}
};
迭代:
/**
* 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:
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
stack<TreeNode*> stk;
if(root==NULL) return sum;
stk.push(root);
while(!stk.empty()){
TreeNode* temp=stk.top();
stk.pop();
if(temp->left&&temp->left->left==NULL&&temp->left->right==NULL)
sum+=temp->left->val;
if(temp->left) stk.push(temp->left);
if(temp->right) stk.push(temp->right);
}
return sum;
}
};