Leetcode 404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
题目大意:
返回给定的二叉树的所有左叶子结点的和。
解题思路:
判断是否为左叶子结点,是则累加。采用递归方式实现。
代码:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root)
return 0;
if(root->left && !root->left->left && !root->left->right)
return sumOfLeftLeaves(root->right) + root->left->val;
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
本文介绍了解决LeetCode404题目的方法,该题目要求求解二叉树中所有左叶子节点的和。通过递归遍历二叉树,判断每个节点是否为左叶子节点并进行累加,最终得到所有左叶子节点的总和。
784

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



