LeetCode 404 左叶子之和 题解
LeetCode链接
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
两种方法:
bfs:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
int sum=0;
while(!queue.isEmpty()){
TreeNode cur=queue.poll();
TreeNode left=cur.left;
TreeNode right=cur.right;
if(left!=null){
if(left.left==null&&left.right==null){
sum+=left.val;
}else {
queue.offer(left);
}
}
if(right!=null&&(right.left!=null||right.right!=null)){
queue.offer(right);
}
}
return sum;
}
}
dfs:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return (root==null)? 0:dfs(root);
}
public int dfs(TreeNode root){
int sum=0;
if(root.left!=null){
sum+=(root.left.left==null&&root.left.right==null)? root.left.val:sumOfLeftLeaves(root.left);
}
if(root.right!=null&&(root.right.left!=null||root.right.right!=null)){
sum+=sumOfLeftLeaves(root.right);
}
return sum;
}
}
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return (root==null)? 0:sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right)+((root.left!=null&&root.left.left==null&&root.left.right==null)?root.left.val:0);
}
}