題目:Sum of 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.
翻譯:
這兒有2個末級左子節點,值分別爲9和15,它們的和是24
答案:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int sum = 0;
if (root == null)
return sum;
TreeNode node = root.left;
if (node != null) {
if (node.left == null && node.right == null)
sum += node.val;
else
sum += sumOfLeftLeaves(node);
}
sum += sumOfLeftLeaves(root.right);
return sum;
}
}
算法說明:
利用遞歸,將末級左節點找到,並將值累加