404. Sum of Left Leaves
1. 题目
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.
2. 题解:
- 解题思路: 递归函数中借助一个变量来标记左右孩子。如果为左孩子,且为叶子结点,则加上此节点的值;如果有节点存在,则遍历右子树
- 代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define RIGHT_CHILD 0
#define LEFT_CHILD 1
int sumOfLeftLeavesRecursion(struct TreeNode* root, int child){
if(NULL == root){
return 0;
}
if(NULL == root->left && NULL == root->right && LEFT_CHILD == child)
return root->val;
return sumOfLeftLeavesRecursion(root->left, LEFT_CHILD) + sumOfLeftLeavesRecursion(root->right, RIGHT_CHILD);
}
int sumOfLeftLeaves(struct TreeNode* root){
if(NULL == root){
return 0;
}
return sumOfLeftLeavesRecursion(root, RIGHT_CHILD);/*根节点需要输出吗??? leetcode结果显示不需要*/
}
- 提交结果: