您的位置:首页 > 其它

[Leetcode]404. Sum of Left Leaves

2017-01-12 15:07 337 查看
题目:

题意: 求二叉树中所有结点的左叶子结点之和

具体代码:

/**
* 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;
}
}
}


代码中注意的问题:首先要判断节点是不是为空才能进行其他判断,否则就会报空指针异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode