404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
就是简单的遍历二叉树,加一个判定条件是否为左叶子节点就行
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
Tra(root,0);
return sum;
}
public void Tra(TreeNode t,int n){
if(t==null) return ;
if(n==1&&t.left==null&&t.right==null) sum+=t.val;
Tra(t.left,1);
Tra(t.right,2);
}
}