原文链接 [每日 LeetCode] 404. Sum of Left Leaves
Description:
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**.
思路:本题要求树中所有左叶子节点的值之和。采用递归方法,检查当前结点的左子结点是否是左结点,如果是的话,则返回左子叶的值加上对当前结点的右子结点调用递归的结果;如果不是的话,我们对左右子结点分别调用递归函数,返回二者之和。
C++ 代码
/** * 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) { if (!root) return 0; if (root->left && !root->left->left && !root->left->right) { return root->left->val + sumOfLeftLeaves(root->right); } return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); } };
运行时间:4ms
运行内存:13.8M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于