LeetCode404左叶子之和

题目链接

https://leetcode-cn.com/problems/sum-of-left-leaves/

题解

  • 自己写的
  • 递归解法
  • 思路见代码注释
// Problem: LeetCode 404
// URL: https://leetcode-cn.com/problems/sum-of-left-leaves/
// Tags: Tree Recursion
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
};

class Solution{
private:
    // 判断一个结点是否为叶子结点:该结点非空且左右孩子为空
    bool isLeaf(TreeNode* root){
        if(root==nullptr)
            return false;
        if(root->left==nullptr && root->right==nullptr)
            return true;
        return false;
    }

public:
    // 得到一颗树的所有左叶子结点的值的总和
    int sumOfLeftLeaves(TreeNode* root){
        if(root==nullptr)
            return 0;
        // 如果左孩子是叶子,则该树的结果为左孩子的值+右子树的结果
        if(isLeaf(root->left))
            return root->left->val + sumOfLeftLeaves(root->right);
        // 如果左孩子不是叶子,则该树对应的值为左子树的结果+右子树的结果
        return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


原文地址:https://www.cnblogs.com/chouxianyu/p/13383976.html