404.leetcode Sum of Left Leaves(easy)[二叉树 递归]

来源:互联网 发布:天刀女捏脸数据导入 编辑:程序博客网 时间:2024/04/30 04:32

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

Example:

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

/** * 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:    void getLeftSum(TreeNode* root,int flag,int &sum)    {        if(root->left != NULL)        {            flag = 1;            getLeftSum(root->left,flag,sum);        }        if(root->right != NULL)        {             flag = 0;            getLeftSum(root->right,flag,sum);        }        if(root->left == NULL && root->right == NULL)        {            if(flag == 1)               sum += root->val;        }        return;    }    int sumOfLeftLeaves(TreeNode* root) {        if(root == NULL) return 0;        int flag = 0;        int sum = 0;        getLeftSum(root,flag,sum);        return sum;    }};


0 0
原创粉丝点击