404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

404. Sum of Left Leaves

左树的值(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; }
}
上一篇:UI Recorder 功能详解


下一篇:IDEA提高开发效率的7个插件