leetcode 404. Sum of Left Leaves DFS深度优先遍历

来源:互联网 发布:奥飞数据 广州 编辑:程序博客网 时间:2024/05/17 23:16

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

Example:

3
/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题意很简单,就是求所有的叶子节点的value的和,

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <bitset>using namespace std;/*struct TreeNode {     int val;     TreeNode *left;     TreeNode *right;     TreeNode(int x) : val(x), left(NULL), right(NULL) {}};*/class Solution {public:    int sumOfLeftLeaves(TreeNode* root)     {        if (root == NULL)            return 0;        else if (root->left != NULL && root->left->left == NULL && root->left->right == NULL)            return root->left->val + sumOfLeftLeaves(root->right);        else            return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);    }};
原创粉丝点击