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.
题目如上。要求出给定根的二叉树的左子叶元素值之和。
思路简析:首先,进行两种情况的判定:空树和只有根的树,其左子叶之和为0。
接着,设计一个递归,把根结点代入:
结束条件:进入循环的结点是叶,返回该结点的关键值;
如果结点有左孩子,count += 左子树进入循环后的返回值;
如果结点有右孩子且右孩子不是叶,count += 右子树进入循环后的返回值。
具体的java代码实现如下:
/**
* 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) {
if ((root == null) || ((root.left == null) && (root.right == null))) return 0;
else return recursion(root);
}
public int recursion(TreeNode root){
int count = 0;
if ((root.left == null) && (root.right == null)) return root.val;
else {
if (root.left != null) count += recursion(root.left);
if ((root.right != null) && ((root.right.left != null) || (root.right.right != null)))
count += recursion(root.right);
}
return count;
}
}