【力扣】404. 左叶子之和

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

示例:

    3
   / \
  9  20
    /  \
   15   7

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

解答:

/**
计算二叉树的所有左叶子之和,就是计算二叉树的左子树的所有左叶子之和,加上二叉树的右子树的所有左叶子之和。
当遇到一棵树,它的左节点恰好是叶子时,则这棵树的所有左叶子之和,就是这个左叶子结点,加上这棵树的右子树的所有左叶子之和。
以上就是递归的主要内容。
递归边界就是遇到空树时,返回0,空树所有左叶子之和显然为0。
*/
/**
 * 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;
        if(root.left != null && root.left.left == null && root.left.right == null)
            return root.left.val + sumOfLeftLeaves(root.right);
        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }
}
发布了233 篇原创文章 · 获赞 254 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_44485744/article/details/104828074
今日推荐