给定二叉树的根节点root
,返回所有左叶子之和。
typedef struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
int sumOfLeftLeaves(struct TreeNode* root)
{
if (root == NULL)
return 0;
//子树找左叶子
int sum = 0;
if (root->left && root->left->left == NULL && root->left->right == NULL)
sum = root->left->val;
return sum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
注:因为是要求和,因此判断出左叶子节点并不能直接返回其值,而是要记录并求和。