题意: 求二叉树中所有结点的左叶子结点之和
具体代码:
/**
* 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){
return 0;
}
int sum = 0;
if (root.left != null && isLeaf(root.left) == true) {
sum += root.left.val;
}
if (root.left != null && isLeaf(root.left) == false) {
sum = sum + sumOfLeftLeaves(root.left);
}
if (root.right != null && isLeaf(root.right) == false) {
sum = sum + sumOfLeftLeaves(root.right);
}
return sum;
}
public boolean isLeaf(TreeNode root) {
if (root != null && root.right == null && root.left == null) {
return true;
} else {
return false;
}
}
}
代码中注意的问题:首先要判断节点是不是为空才能进行其他判断,否则就会报空指针异常