404. Sum of Left Leaves(C语言)

xiaoxiao2021-02-28  101

Find the sum of all left leaves in a given binary tree.

Example:

3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

我是看了答案才觉得其实明白了题意,答案也就出来了

求树里面,所有有左孩子,而左孩子没有孩子的这样的左孩子值的和

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int sumOfLeftLeaves(struct TreeNode* root) { if(root==NULL){ return 0; } if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){ return root->left->val+sumOfLeftLeaves(root->right); } return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right); }

转载请注明原文地址: https://www.6miu.com/read-71370.html

最新回复(0)