题目:
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.
翻译:
给定一棵二叉树,找到所有左叶子的和。
例子:
3 / \ 9 20 / \ 15 7 二叉树中有两个左叶子,它们的值分别为9和15。返回24。
思路:
递归,注意边界:
if((root->left!=NULL)&&(root->left->right==NULL)&&(root->left->left==NULL))
sum = root->left->val;
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
using namespace std;
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 0;
int sum = 0;
if((root->left!=NULL)&&(root->left->right==NULL)&&(root->left->left==NULL))
sum = root->left->val;
return sum + sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};
int main()
{
Solution s;
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
int result;
result = s.sumOfLeftLeaves(root);
cout << result;
return 0;
}