计算给定二叉树的所有左叶子之和.
示例:
8
/ \
5 20
/ \
11 23
在这个二叉树中,有两个左叶子,分别是 5 和 11,所以返回 16
一个节点为左叶子节点,当且仅当它是某个节点的左子节点,并且它是一个叶子结点。因此我们可以考虑对整棵树进行遍历,当我们遍历到节点时,如果它的左子节点是一个叶子结点,那么就将它的左子节点的值累加计入答案。
package com.loo;
public class LeftLeafSum {
static class TreeNode {
TreeNode left;
TreeNode right;
int value;
TreeNode(int v) {
value = v;
}
}
/**
* @param args
* 6
* / \
* 4 8
* / \ / \
* 1 5 7 9
* /
* 10
*/
public static void main(String[] args) {
TreeNode root = new TreeNode(6);
TreeNode l1 = new TreeNode(4);
TreeNode l2 = new TreeNode(1);
TreeNode l3 = new TreeNode(5);
TreeNode r1 = new TreeNode(8);
TreeNode r2 = new TreeNode(7);
TreeNode r3 = new TreeNode(9);
TreeNode r4 = new TreeNode(10);
root.left = l1;
l1.left = l2;
l1.right = l3;
root.right = r1;
r1.left = r2;
r1.right = r3;
r3.left = r4;
System.out.println(leftLeafSum(root));
}
private static int leftLeafSum(TreeNode root) {
int sum = 0;
if (root == null) {
return 0;
}
if (root.left != null) {
if (isLeaf(root.left)) {
sum += root.left.value;
} else {
sum += leftLeafSum(root.left);
}
}
if (root.right != null && !isLeaf(root.right)) {
sum += leftLeafSum(root.right);
}
return sum;
}
private static boolean isLeaf(TreeNode root) {
if (root == null) {
return true;
}
return root.left == null && root.right == null;
}
}