Find the sum of all left leaves in a given binary tree.
样例
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
解题思路:
递归。如何判断一个节点是左叶子节点(解决这个问题的核心):对于一个节点root,root.left不为空,且 root.left.letf、root.left.right为空,则root.left这个节点是左叶子节点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: t
* @return: the sum of all left leaves
*/
int sumOfLeftLeaves(TreeNode * root)
{
// Write your code here
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);
}
};