zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Eclipse MarketPlace 打不开,对话框闪退
    docker 创建容器的时候的坑
    win7 设置docker加速器
    postgres常用命令
    docker加速器配置
    docker 安装 postgresql
    Spring Cloud-服务的注册与发现之服务注册中心(Eureka Server)
    redis incr自增指定的无限期 key 删除问题
    redis读取自增时候指定的key问题
    docker 安装 redis
  • 原文地址:https://www.cnblogs.com/VickyWang/p/5998855.html
Copyright © 2011-2022 走看看