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;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int count=0;
if(root==NULL){
return NULL;
}
if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){
count+=root->left->val;
}
count+=sumOfLeftLeaves(root->left);
count+=sumOfLeftLeaves(root->right);
return count;
}
};
本文介绍了一种算法,用于求解给定二叉树中所有左叶子节点的值之和。通过递归遍历的方式找到每一个左叶子节点并累加其值,最终返回总和。
355

被折叠的 条评论
为什么被折叠?



