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 };
  • 相关阅读:
    安卓linux真机调试
    Java开发必装的IntelliJ IDEA插件
    在switch中的case语句中声明变量会被提前
    PostgresSQL 数组包含@>
    SQL 增加列、修改列、删除列
    ConcurrentHashMap 的实现原理
    Apache——DBUtils框架ResultSetHandler接口使用
    [转](不理想)Ubuntu下更改主显示器
    [问题记录]Java关于可变参数重载问题的测试
    使用openssl生成双向加密证书(转)
  • 原文地址:https://www.cnblogs.com/VickyWang/p/5998855.html
Copyright © 2011-2022 走看看