LeetCode题解之 Sum of Left Leaves

1、题目描述

2、问题分析

对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可。

3、代码

 1 int sumOfLeftLeaves(TreeNode* root) {
 2         if (root == NULL)
 3             return 0;
 4         int ans = 0;
 5         if (root->left != NULL) {
 6             if (root->left->left == NULL && root->left->right == NULL) 
 7                 ans += root->left->val;
 8             else 
 9                 ans += sumOfLeftLeaves(root->left);
10         }
11         
12         ans += sumOfLeftLeaves(root->right);
13         
14         return ans;
15         
16     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/10436506.html
今日推荐