【easy】404. Sum of Left Leaves

时间:2023-03-09 17:00:31
【easy】404. 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 ;
else if(root->left!=NULL && root->left->left==NULL && root->left->right==NULL) //相当于递归的终止情形
return root->left->val+sumOfLeftLeaves(root->right);
else
return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
//这个题分成以下几种情况进行讨论
//--如果当前节点是空,毫无疑问返回0
//--如果有左节点,但是左节点没有任何的子节点(左节点的值+右子树的和)
//--其他的情况:左子树和+右子树和 //傻孩子,这是你想的最好,但是错的最离谱的一次
/*
if (root == NULL || (root->left == NULL && root->right == NULL))
return 0;
if (root->left == NULL && root->right != NULL)
return sumOfLeftLeaves(root->right);
if (root->left != NULL && root->right == NULL)
return root->left->val + sumOfLeftLeaves(root->left);
if (root->left != NULL && root->right != NULL)
return root->left->val + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
*/
}
};