1. 程式人生 > 實用技巧 >LeetCode404左葉子之和

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/

歡迎討論和交流!