• LeetCode 404 Sum of Left Leaves


    Problem:

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

    Summary:

    求左子叶之和。

    Analysis:

    1. 求左子叶之和,即需要遍历整棵二叉树,常规的方法则为递归。首先我想到的是调用子函数,在子函数中递归,每递归至一个新的节点,首先传入bool类型标记是根节点的左子树还是右子树。若为左子树,且为叶子节点,则将当前节点的value计入和中。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int sumOfLeftLeaves(TreeNode* root) {
    13         if (root == NULL) {
    14             return 0;
    15         }
    16         
    17         int sum = 0;
    18         calLeftLeaves(root->left, true, sum);
    19         calLeftLeaves(root->right, false, sum);
    20         
    21         return sum;
    22     }
    23 
    24 private:
    25     void calLeftLeaves(TreeNode* root, bool left, int& sum) {
    26         if (root == NULL) {
    27             return;
    28         }
    29         
    30         if (left && (root->left == NULL) && (root->right == NULL)) {
    31             sum += root->val;
    32         }
    33         
    34         calLeftLeaves(root->left, true, sum);
    35         calLeftLeaves(root->right, false, sum);
    36     }
    37 };

     2. 进一步简化代码,试图不掉用子函数,在主函数中进行递归操作。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int sumOfLeftLeaves(TreeNode* root) {
    13         if (root == NULL) {
    14             return 0;
    15         }
    16         
    17         if (root->left && root->left->left == NULL && root->left->right == NULL) {
    18             return root->left->val + sumOfLeftLeaves(root->right);
    19         }
    20         
    21         return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    22     }
    23 };
  • 相关阅读:
    HCIA-IoT 华为认证物联网工程师
    [书目20210522]投资最重要的事
    [书目20210414]海龟交易法则
    [书目20210224]陆蓉 行为金融学讲义
    [书目20210207]肖星的财务思维课
    [转]昂克英文君 一张图告诉你英语该怎么学
    Cloud Native
    Aerospike-介绍
    Groovy使用场景
    javaStream与响应式流
  • 原文地址:https://www.cnblogs.com/VickyWang/p/5998855.html
Copyright © 2020-2023  润新知