题目描述,链接https://leetcode-cn.com/problems/sum-of-left-leaves/
解题代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
//注意是左叶子节点,不是所有的左孩子节点。之前算成左孩子节点了,导致错误
if(root==NULL){
return 0;
}
int sum = 0;
traversal(sum, root);
return sum;
}
void traversal(int& sum, TreeNode* root){
if(root->left!=NULL){
if(root->left->left==NULL && root->left->right==NULL){
sum += root->left->val;
}
traversal(sum, root->left);
}
if(root->right!=NULL){
traversal(sum, root->right);
}
}
};
运行结果
运行结果不稳定,有时用时0ms,有时4ms,有时8ms。但是内存消耗始终是13.1MB左右