题:https://leetcode.com/problems/sum-of-left-leaves/description/
题目
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.
题目大意
求所有左叶子的和。其中左叶子的定义为:1.为叶子;2.为某结点的左子树。
思路
先序遍历,若一个结点为左子树为 叶子,那么累加。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int tsum = 0;
public void dfs(TreeNode root){
if(root == null)
return;
if(root.left != null && root.left.left == null && root.left.right == null)
tsum += root.left.val;
dfs(root.left);
dfs(root.right);
}
public int sumOfLeftLeaves(TreeNode root) {
dfs(root);
return tsum;
}
}