本题计算二叉树的左叶子之和,使用后序遍历的顺序对二叉树进行深度搜索,关键点在于,对左叶子节点的值的操作上,需要在左叶子节点的父节点进行。
/**
* 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 dfs(TreeNode* root, int & sum){
if(root->left == nullptr && root->right == nullptr){
return;
}
if(root->left){
dfs(root->left, sum);
}
if(root->right){
dfs(root->right, sum);
}
if(root->left != nullptr && root->left->left == nullptr && root->left->right ==nullptr){
sum += root->left->val;
}
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if(root == nullptr){
return 0;
}
dfs(root, sum);
return sum;
}
};