我的非递归代码
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
Queue<TreeNode> tem = new LinkedList<>();
if(root == null){
return 0;
}
tem.offer(root);
int sum = 0;
while (!tem.isEmpty()) {
int size = tem.size();
for (int i = 0; i < size; i++) {
TreeNode tem1 = tem.poll();
if(tem1.left != null ){
tem.offer(tem1.left);
if(tem1.left.left == null && tem1.left.right == null){
sum+=tem1.left.val;
}
}
if(tem1.right !=null){
tem.offer(tem1.right);
}
}
}
return sum;
}
}
效率还行
一直考虑如何使用递归来进行求解,奈何一点思路都没
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
if(root.left!=null && root.left.left==null && root.left.right==null){
return root.left.val+sumOfLeftLeaves(root.right);
}
else{
return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
}
}
}