【LeetCode】404. Sum of Left Leaves

来源:互联网 发布:网贷安卓源码 编辑:程序博客网 时间:2024/06/08 03:55

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.

方法1:

class Solution {public:    int sum=0;    void DFS(TreeNode* root,int dir){        if(!root)return;        if(dir==1&&!root->left&&!root->right){            sum+=root->val;        }        DFS(root->left,1);        DFS(root->right,2);    }    int sumOfLeftLeaves(TreeNode* root) {        DFS(root,0);        return sum;    }};

方法2:

class Solution {public:    int sumOfLeftLeaves(TreeNode* root) {        if(!root)return 0;        else if(root->left&&!root->left->right&&!root->left->left) return root->left->val+sumOfLeftLeaves(root->right);        else return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);    }};
原创粉丝点击