递归方法:
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){return 0;
}
int sum=0;
Stack<TreeNode> stacknode= new Stack<>();
stacknode.push(root);
while(!stacknode.isEmpty()){
root=stacknode.pop();
if(root.left!=null&&root.left==null&&root.right==null){ //判断左树叶
sum=sum+root.left.val;
}
if(root.left!=null){
stacknode.push(root.left);
}
if(root.right!=null){
stacknode.push(root.right);
}
}
return sum;
}
迭代方法
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.right)+sumOfLeftLeaves(root.left);
}
}
先写出了迭代的方法,递归还是掌握不熟练,改了好多次。