C++Leetcode404:左叶子之和

题目
计算给定二叉树的所有左叶子之和。

示例:
在这里插入图片描述
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24。

思路
昨天想这道题一个小时左右没做出来,晚上躺在床上接着想,后来突然想到:只要把判断右叶子的条件加到递归里面就可以了,其他都不用变。就迫不及待的想要试一下,果不其然~哒哒,提交成功了!
1、递归再求和。先采用递归的方法,求得所有的左叶子节点保存在一个动态数组中,然后再遍历数组求和。这种方法在空间和时间上,都不占优势,但可以得到所有的左叶子节点。
2、递归直接求和。做递归的时候,传递一个int的引用,直接进行求和。

实现方法
一、递归再求和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        vector<int> res,s;
        s=leftLeaf(root,res);
        if(s.size()==1 && s[0]==root->val) return 0; //如果只有根结点,则返回0
        int sum=0;
        for(int i=0;i<s.size();i++){    //遍历数组求和
            sum += s[i];
        }
        return sum;
    }
    vector<int> leftLeaf(TreeNode* root, vector<int> &res){
        if(!root) return res;
        if(!root->left && !root->right) res.push_back(root->val);
        if(root->left) leftLeaf(root->left,res);
        if(root->right) { 
            if(!root->right->left && !root->right->right) return res;
            leftLeaf(root->right,res);
        }
        return res;
    }
};

二、递归直接求和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        int sum=0;
        if(root && !root->left && !root->right) return 0;
        sumLeftLeaves(root,sum);
        return sum;
    }
     
    void sumLeftLeaves(TreeNode* root,int &sum){
        if(!root) return;
        if(!root->left && !root->right) sum += root->val;
        if(root->left) sumLeftLeaves(root->left,sum);
        if(root->right){
            if(!root->right->left && !root->right->right) return;
            sumLeftLeaves(root->right,sum);
        } 
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43434305/article/details/87872471