letecode [404] - Sum of Left Leaves
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==NULL) return 0; int sum = 0; if(root->left!=NULL && root->left->left==NULL && root->left->right==NULL) sum += root->left->val;; sum += sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); return sum; } };
运行结果:
执行用时 :8 ms, 在所有 C++ 提交中击败了85.89%的用户
内存消耗 :13.6 MB, 在所有 C++ 提交中击败了79.31%的用户