Find the sum of all left leaves in a given binary tree.
左树的值(9+15=24)
/**
* 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 ans=0;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root); while(!stack.empty()){
TreeNode node=stack.pop(); if(node.left!=null&&node.left.left==null&&node.left.right==null){ ans+=node.left.val; }
if(node.right!=null){ stack.push(node.right);
}
if(node.left!=null){ stack.push(node.left);
} } return ans; }
}