LeetCode/404. 左叶子之和

404. 左叶子之和

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题解:

本题我们需要明确, 只有左右孩子节点都为空的节点才可以称为叶子节点,我们只需要深度优先搜索遍历树,找到满足要求的节点,将其值累计啊即可。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int result = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
dfs(root);
return result;
}

void dfs(TreeNode root) {
if (root.left == null && root.right == null) return;
if (root.left != null) {
if (root.left.left == null && root.left.right == null)
result += root.left.val;
else dfs(root.left);
}
if (root.right != null)
dfs(root.right);
}
}

Comments