leetCode404

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36257146/article/details/102694593

递归再递归

/**
 * 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 ans = 0;
        if(!root) return 0;
        sum(root,root->right,ans);
        sum(root,root->left,ans);
        return ans;
    }
    void sum(TreeNode* q,TreeNode* p,int& ans)
    {
        if(!p) return;
        else if(!p->left && !p->right)
        {
            if(q->left == p)
            {
                ans+= p->val;
                return;
            }
            else return;
        }
        sum(p,p->left,ans);
        sum(p,p->right,ans);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36257146/article/details/102694593