前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:404. Sum of Left Leaves

LeetCode笔记:404. Sum of Left Leaves

作者头像
Cloudox
发布2021-11-23 15:50:30
1190
发布2021-11-23 15:50:30
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

Find the sum of all left leaves in a given binary tree. Example:

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

大意:

计算一个二叉树中所有左叶子节点的和 例子:

在这个二叉树中有两个左叶子节点,分别为9和15。因此返回24。

思路:

从思路来说也没有什么特别的地方,就是去做判断,细心一点不要有漏洞就好。 大体上分为判断有没有左节点和有没有右节点。如果有左节点,看左节点有没有子节点,没有(即左叶子节点)则直接用起值去加,有则继续对左节点递归。如果有右节点,且右节点有子节点,则对右节点递归,否则不管是没有右节点还是右节点没有子节点(即右叶子节点)都直接看做加0。需要注意的是如果本身节点自己是null,要返回0。另外如果只有根节点自己,也要返回0,因为题目说的是左叶子节点,根节点是不算的。最后要注意的就是在判断所有节点的子节点或者值之前,要对该节点本身是否为null做出判断,否则会有错误的。

代码(Java):

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        else if (root.left == null && root.right == null) return 0;
        else {
            return ((root.left != null && root.left.left == null && root.left.right == null) ? root.left.val : sumOfLeftLeaves(root.left)) + ((root.right != null && (root.right.left != null || root.right.right != null)) ? sumOfLeftLeaves(root.right) : 0);
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档