2022.2.27 LeetCode —— 二叉树


一、今日刷题

1. 第七部分:二叉树 – 404. 左叶子之和

跳转LeetCode

给定二叉树的根节点 root ,返回所有左叶子之和。
在这里插入图片描述


答案代码

自己的思路,参考题解的代码:做题时意识到了要想判断某节点是否为左叶子,必须要通过节点的父节点来判断其左孩子是不是左叶子。如果该节点的左节点不为空,该节点的左节点的左节点为空,该节点的左节点的右节点为空,则找到了一个左叶子。
但在写代码时,把 sum 作为了函数的一个参数,像题解这样写在方法外是很好的。

package BinaryTree;

/**
 * @author: LYZ
 * @date: 2022/2/27 14:28
 * @description: 404. 左叶子之和
 */
public class SumOfLeftLeaves {
    public static void main(String[] args) {
        TreeNode p = new TreeNode(1, new TreeNode(1, new TreeNode(2), new TreeNode(3)), new TreeNode(6));
        SumOfLeftLeaves sumOfLeftLeaves = new SumOfLeftLeaves();
        int ans = sumOfLeftLeaves.sumOfLeftLeaves(p);
        System.out.println(ans);
    }

    public int sumOfLeftLeaves(TreeNode root) {
        countSum(root);
        return sum;
    }

    int sum = 0;

    public void countSum(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            if (root.left.left == null && root.left.right == null) {
                sum += root.left.val;
            }
        }

        countSum(root.left);
        countSum(root.right);
    }
}

明天就开学了,希望能保持每天刷题写博客的节奏,并且在这里记录一下课内遇到的问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值