原题链接:https://leetcode.com/problems/sum-of-left-leaves/
1. 题目介绍
Find the sum of all left leaves in a given binary tree.
给出一个二叉树,计算所有左叶子节点的val值之和。
Example:
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
有两个左叶子节点,分别是 9 和15。返回他们的总和24.
2. 解题思路
这道题目可以使用深度优先搜索 + 递归做。按照深度优先搜索的顺序遍历每个节点,如果发现这个节点的左节点是叶子节点的话,就加上该叶子节点的val值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null ){
return 0;
}
int k = 0;
//判断root的左节点是否为叶子节点
if(root.left != null && root.left.left == null && root.left.right == null){
k = root.left.val;
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + k;
}
}