leetcode解题: Sum of Left Leaves (404)

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.

解法1:Recursion O(N) Time

二叉树很自然的想到用递归的办法解决。这里的难点是要记录每一个节点是否为Left child/right child,为此我们需要有一个helper函数来记录。根据OA的结果,root是算作非左子树的。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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) {
return helper(root, false);
}
int helper(TreeNode* root, bool isleft) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) {
return isleft? root->val: 0;
}
int left = helper(root->left, true);
int right = helper(root->right, false);
return left + right;
}
};

Java

1