404. 左叶子之和

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

示例:

3
/ \
9 20
/ \
15 7

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves

 1 public class SumofLeftLeaves {
 2     static class TreeNode {
 3         int val;
 4         TreeNode left;
 5         TreeNode right;
 6         TreeNode(int x) {
 7             val = x;
 8         }
 9     }
10     
11     public int sumOfLeftLeaves(TreeNode root) {
12         if(root == null) {
13             return 0;
14         }
15         //如果当前节点的左节点是叶子节点,则返回左结点值+右子节点的递归结果
16         if(isLeft(root.left)) {
17             return root.left.val + sumOfLeftLeaves(root.right);
18         }
19         //如果当前节点的左、右节点都不是叶子节点,则分别对其左右节点进行递归
20         int leftSum = sumOfLeftLeaves(root.left);
21         int rightSum = sumOfLeftLeaves(root.right);
22         return leftSum + rightSum;
23     }
24     
25     public static boolean isLeft(TreeNode node) {
26         if(node == null) {
27             return false;
28         }
29         return (node.left == null) && (node.right == null);
30     }    
31 }

 

posted @ 2019-06-29 17:14  往南的小燕子  阅读(131)  评论(0编辑  收藏  举报