Leetocde 404. 左叶子之和

  1. 左叶子之和

给定二叉树的根节点 root ,返回所有左叶子之和。
sample1
sample2

提示:

  • 节点数在 [1, 1000] 范围内
  • -1000 <= Node.val <= 1000

采用的是递归法

s1. 确定递归函数的参数和返回值
s2. 确定终止条件

if(root == NULL)
            return 0;

s3. 确定单层递归的逻辑

  • 当遇到左叶子节点的时候,记录数值,然后通过递归求取左子树左叶子之和,和 右子树左叶子之和,相加即可。

AC:文章来源地址https://uudwc.com/A/Pmgjb

/*
 * @lc app=leetcode.cn id=404 lang=cpp
 *
 * [404] 左叶子之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL)
            return 0;
        int leftValue = 0;
        if(root->left && !(root->left->left) && !(root->left->right))
        {
            leftValue = root->left->val;
        }
        return leftValue + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};
// @lc code=end

原文地址:https://blog.csdn.net/qq_54053990/article/details/133244793

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

上一篇 2023年09月25日 06:43
【已解决】qt.qpa.plugin: Could not load the Qt platform plugin “windows“ in ““ even though it was found.
下一篇 2023年09月25日 06:43